您的位置:首页 > 其它

【leetcode】Remove Duplicates from Sorted Array 1和2

2014-09-05 16:56 344 查看
双指针的问题,去掉冗余元素的时候,数据结构是数组的时候常常采用

1题目:

Given input array A =
[1,1,2]
,

Your function should return length =
2
, and A is now
[1,2]
.
class Solution {
public int removeDuplicates(int[] A) {
int length=A.length;
int index=0;
for(int i=0;i<length;i++){
for(int j=i+1;j<length;j++){
if(A[i]!=A[j]){
break;
}
else{
i++;
}
}
A[index++]=A[i];
}
return index;
}
}
题目2:比题目一多的条件是相同的元素可以最多存在两次,所以加入一个count计算重复元素出现的次数,注意count是从1开始的

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 length=A.length;
int index=0;
int count=0;
for(int i=0;i<length;i++){
count=1;//此处需注意
for(int j=i+1;j<length;j++){
if(A[i]!=A[j]){
break;
}
else{
count++;
i++;
}
}
if(count>=2)
{
A[index++]=A[i];
A[index++]=A[i];
}
else
A[index++]=A[i];
}
return index;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: