LeetCode #27 Remove Element

LeetCode #27 Remove Element

Question

Given an array and a value, remove all instances of that value in place and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example:
Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.

Solution

Approach #1

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).

Space complexity: O(1).

Approach #2

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).

Space complexity: O(1).

转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/7066278.html

posted on 2017-06-23 17:12  Silence_cnblogs  阅读(222)  评论(0编辑  收藏  举报