[LeetCode] 080: Remove Duplicates from Sorted Array

来源:互联网 发布:点餐系统数据库设计 编辑:程序博客网 时间:2024/05/21 15:10
[Problem]

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


[Solution]
class Solution {
public:
int removeDuplicates(int A[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(n <= 1)return n;
int i = 0, j = 0;
while(j < n){
if(j > i && A[i] != A[j]){
A[++i] = A[j];
}
j++;
}
return i+1;
}
};
说明:版权所有,转载请注明出处。Coder007的博客
阅读全文
0 0
原创粉丝点击