您的位置:首页 > 其它

LeetCode - Remove Duplicates from Sorted Array

2014-01-14 04:03 197 查看
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].

http://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/

Solution:

Since the array is sorted, we can scan from the head and check if A[i] == A[i+1]. And use a new index to store the position. And the final result of index is also the length of the new array. Be careful about the value of the new index and array overflow.

https://github.com/starcroce/leetcode/blob/master/remove_duplicates_from_sorted_array.cpp
// 72 ms for 160 test cases
// Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
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 index = 1, current = 1;
while(current < n) {
if(A[current] == A[current-1]) {
current++;
continue;
}
A[index] = A[current];
index++;
current++;
}
return index;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode array