Given an array and a value, remove all instances of that value in place and return the new length.html
Do not allocate extra space for another array, you must do this in place with constant memory.swift
The order of elements can be changed. It doesn't matter what you leave beyond the new length.app
Example:
Given input array nums = [3,2,2,3]
, val = 3
this
Your function should return length = 2, with the first two elements of nums being 2.spa
class Solution { func removeElement(_ nums: inout [Int], _ val: Int) -> Int { var i = 0 for j in 0..<nums.count { if nums[j] != val { nums[i] = nums[j] i += 1 } } return i } }
Time complexity: O(n).code
Space complexity: O(1).htm
class Solution { func removeElement(_ nums: inout [Int], _ val: Int) -> Int { var i = 0 var n = nums.count - 1 while i <= n { if nums[i] == val { nums[i] = nums[n] n -= 1 } else { i += 1 } } return i } }
Time complexity: O(n).blog
Space complexity: O(1).element
轉載請註明出處:http://www.cnblogs.com/silence-cnblogs/p/7066278.htmlleetcode