[C++]LeetCode: 2 Remove Duplicates from Sorted Array

来源:互联网 发布:掌控网络 编辑:程序博客网 时间:2024/05/02 01:00

题目:

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

思路:只需要把每个不重复数字按顺序存储到一起即可;设置两个下标i,j,使用j遍历数组, i是标记,标记每段重复的开始数字,后面的数字也是和A[i]比较;j是把尺子在数组内移动。

Attention: 注意思考没有重复数字的特殊情况。

AC code:

class Solution {public:    int removeDuplicates(int A[], int n) {        //只需要把每个不重复数字按顺序存储到一起即可        if(n == 0) return 0;                //i是标记,标记每段重复的开始数字,后面的数字也是和A[i]比较;j是把尺子在数组内移动        int i = 0, j = 1;                while(j < n)        {            if(A[j] == A[i])            {                j++;            }            else            {                A[++i] = A[j++];            }        }                return i + 1;    }    };



0 0
原创粉丝点击