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

Leetcode (6) Remove Duplicates from Sorted Array

时间:2015-04-11 18:02:04      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c++   算法   

题目描述

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].

解题思路

题目要求去除排序数组中多余的元素,改变数组并返回新数组的个数。也就是说原数组为A = [1,1,2],处理后的结果应该为A = [1,2,*],即将不同的元素2放在了1后面,且返回数组的长度为2.

该方法可以通过使用两个数组序号index或者指针实现。第一个index指向最后一个有效元素,第二个index向后遍历,若当前遍历元素与index元素不同,则将index后移一位,并将第二个index指向的元素付给第一个index的元素。最后返回index的位置即可。用时39 ms,比较慢~不知道大家有没有更好的想法,欢迎留言~~~~

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

Leetcode (6) Remove Duplicates from Sorted Array

标签:leetcode   c++   算法   

原文地址:http://blog.csdn.net/angelazy/article/details/44996391

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