美文网首页
【Leetcode】26. Remove Duplicates

【Leetcode】26. Remove Duplicates

作者: 随时学丫 | 来源:发表于2018-12-15 23:51 被阅读12次

【Leetcode】26. Remove Duplicates from Sorted Array

26.Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)

Easy

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

Do not allocate extra space for another array, you must do this by modifying the input array in-placewith O(1) extra memory.

Example 1:

Given 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 returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

已排好序的数组,只能 in place 替换,不能用额外数组,并且要求结果返回unique的长度。

题解

方法是双指针,一个指针只记录unique的并且帮助记录长度,一个指针往前找。

class Solution {
    public int removeDuplicates(int[] A) {
        if(A == null || A.length==0) return 0;
        int len=1;
        int n = A.length;
        for(int i=1; i<n; i++) {
            if(A[i] != A[i-1]) {
                if(A[i] != A[len])
                    A[len] = A[i];
                len++;
            }
        }
        return len;
    }
}

Runtime: 10 ms, faster than 38.40% of Java online submissions for Remove Duplicates from Sorted Array.

相关文章

网友评论

      本文标题:【Leetcode】26. Remove Duplicates

      本文链接:https://www.haomeiwen.com/subject/cdwzhqtx.html