一起刷leetcode(26):Remove Duplicates from Sorted Array


问题:Remove Duplicates from Sorted Array
来源:https://leetcode.com/problems/ ... rray/
问题描述:

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].
已邀请:

青原行思 - Crazy about ML!

赞同来自: July 笑由心生


试过移位和将重复元素置为下一大小的数,均超时。
好不容易才想到现在这个方法,过程还是很曲折的,但是整个思考的过程很值。

Always concentrate on what you want,get rid of other things;
Just make it simple and stupid.
/*--------------------------
* Date:2015-03-10
* Author:qingyuanxingsi
* Title:26.Remove Duplicates from Sorted Array
* Link:https://leetcode.com/problems/remove-duplicates-from-sorted-array/
* Result:AC
*/
class Solution {
public:
    int removeDuplicates(int A[], int n) {
        int i=0,j=0;
        while(j<n){
            while(A[i] == A[j]){
                j++;
            }
            A[++i]=A[j];
        }
        return i;
    }
};

要回复问题请先登录注册

收藏七月在线,一起向大牛进阶

ctrl+D或command+D可以快速收藏哦~