码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Duplicates from Sorted Array

时间:2015-04-16 06:42:09      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

题目链接https://leetcode.com/problems/remove-duplicates-from-sorted-array/

 

思路就是维护两个pointer,一个,i, 用于遍历整个数组,另一个,len, 用于保存当前的无重复元素的数组的最后一个position

if A[i] == A[len], A[i]重复,跳过,i++;

if A[i] != A[len], 把A[i]放到A[len+1],A[len + 1] = A[i], i++, len++;

 

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if(n == 0) return 0;
        int len = 0;
        for(int i = 1; i < n; i++) {
            if(A[i] != A[len]) {
                len++;
                A[len] = A[i];
            }
        }
        return len + 1;
    }
};

Reference:

  http://bangbingsyb.blogspot.com/2014/11/leetcode-remove-duplicates-from-sorted.html

Remove Duplicates from Sorted Array

标签:

原文地址:http://www.cnblogs.com/walcottking/p/4430823.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!