26. Remove Duplicates from Sorted Array

来源:互联网 发布:linux系统改编码 编辑:程序博客网 时间:2024/05/24 06:14

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.

这个题我刚看的时候感觉很简单,也没有仔细看,直接就把数组存进了set里,结果submit不过,细看下才发现原来是个sorted数组!审题很重要……

思路如下:

用cur表示不重复的数组的长度,即最后要返回的去重后的数组长度。从下标1开始循环遍历数组,如果第i-1和第i个不相等,那么就将第i个的值赋值给第cur个,这样遍历数组后,数组的前cur个元素就是我们要的去重后的数组。例如数组[1,1,2,2,3,4],按此原理执行一遍后变成了[1,2,3,4,3,4]

代码如下:

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

运行时间:

39ms

1 0