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

去掉有序数组中重复数字 原地 leetcode java (最简单的方法)

2014-07-09 20:21 681 查看
1.利用荷兰国旗的思路,每次记住最后一个位置,遇到一个不重复的数,放在它后面,代码很简单。

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

public class Solution {
public int removeDuplicates(int[] A) {
int len=A.length;
if(len==0) return 0;
int pos=0;

for(int i=1;i<len;i++)
{
if(A[i]!=A[pos])
{
pos++;
A[pos]=A[i];

}

}
return pos+1;

}

}


View Code
2.只要跟end的前一个比较就行了,思路跟上边,就一点不一样,原创啊

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array A =
[1,1,1,2,2,3]
,

Your function should return length =
5
, and A is now
[1,1,2,2,3]
.

public class Solution {
public int removeDuplicates(int[] A) {
int len=A.length;
if(len==0) return 0;
if(len==1) return 1;
int end=1;
for(int i=2;i<len;i++)
{
if(A[i]!=A[end-1])
{
end++;
A[end]=A[i];

}

}

return end+1;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐