LeetCode #26 Remove Duplicates from Sorted Array

LeetCode #26 Remove Duplicates from Sorted Array

Question

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

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

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

Solution

Approach #1

class Solution {
    func removeDuplicates(_ nums: inout [Int]) -> Int {
        if nums.count == 0 { return 0 }
        var i = 0
        for j in 1..<nums.count {
            if nums[i] != nums[j] {
                i += 1
                nums[i] = nums[j]
            }
        }
        return i + 1
    }
}

Time complexity: O(n).

Space complexity: O(1).

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

posted on 2017-06-23 15:24  Silence_cnblogs  阅读(157)  评论(0编辑  收藏  举报