Remove Duplicates from Sorted Array

来源:互联网 发布:淘宝阿里云 编辑:程序博客网 时间:2024/05/18 00:52

Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear onlyonce 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].

 

题解:

双指针思想。并且保存前面遍历的元素的值。用以判断是否将新遍历的元素加入到数组中。

 

Code:

class Solution {public:    int removeDuplicates(int A[], int n){int preElement=0;int pCur=0;for(int i=0;i<n;i++){if(i==0){preElement=A[i];A[pCur++]=A[i];}else{if(preElement!=A[i]){A[pCur++]=A[i];preElement=A[i];}}}return pCur;}};
0 0
原创粉丝点击