您的位置:首页 > 编程语言 > Java开发

LeetCode | Remove Duplicates from Sorted Array

2014-04-03 15:16 435 查看
题目

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]
.
分析
Remove Element神似

代码

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