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

Remove Duplicates from Sorted Array---leetcode 我的java题解

2015-03-26 15:45 281 查看
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]
.

这题比较简单。关键是设置一个index,指向要复盖掉重复数据的位置。从第2个数开始与前一个数比较。只要不同,就标记下要覆盖。

我写的java程序:



public int removeDuplicates(int[] A) {

int index=1;

if(A.length==0||A==null) return 0;

for(int i=1;i<A.length;i++){

if(A[i]!=A[i-1]) {

A[index] = A[i];

index++;

}

}

return index;

}

网上看到别人的写法 ,感觉更熟练。
public int removeduplicates1(int[] A){

if (A.length == 0) return 0;

int index = 0;

for (int i = 1; i < A.length; i++) {

if (A[index] != A[i])

A[++index] = A[i];

}

return index + 1;

}

===========

A[++index]这个用的挺简洁的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: