码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode] Remove Duplicates from Sorted Array 有序数组中去除重复项

时间:2015-03-11 10:40:39      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

 

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 A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

 

这道题要我们从有序数组中去除重复项,和之前那道 Remove Duplicates from Sorted List 移除有序链表中的重复项 的题很类似,但是要简单一些,因为毕竟数组的值可以通过下标直接访问,而链表不行。那么这道题的解题思路是,我们使用快慢指针来记录遍历的坐标,最开始时两个指针都指向第一个数字,如果两个指针指的数字相同,则快指针向前走一步,如果不同,则两个指针都向前走一步,这样当快指针走完整个数组后,慢指针当前的坐标加1就是数组中不同数组的个数,代码如下:

 

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if (n <= 1) return n;
        int pre = 0, cur = 0;
        while (cur < n) {
            if (A[cur] == A[pre]) ++cur;
            else A[++pre] = A[cur++];
        }
        return pre + 1;
    }
};

 

[LeetCode] Remove Duplicates from Sorted Array 有序数组中去除重复项

标签:

原文地址:http://www.cnblogs.com/grandyang/p/4329128.html

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