您的位置:首页 > 其它

Leetcode -- Remove Duplicates from Sorted Array

2015-01-03 17:13 363 查看
问题链接:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/

问题描述:

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

API:public int removeDuplicates(int[] A)

问题分析:这一题其实很简单,就是给一个慢指针去计算答案数目即可,不符合A[i] == A[i - 1]的当前计数器index就可以获得A[i],计数器就可以加一。

给出代码如下:

public int removeDuplicates(int[] A) {
int slow = 1;
for(int i = 1; i < A.length; i++){
if(A[i] != A[i - 1]){
A[slow] = A[i];
slow++;
}
}
return A.length == 0 ? 0 : slow;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: