您的位置:首页 > 其它

[leetcode] Remove Duplicates from Sorted Array

2014-04-24 12:36 218 查看
描述

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+1 就是长度。

算法解释:循环访问原数组元素,设置一个Index 标示需要覆盖的字符。 遇到重复相等的字符时 index 保持不变,  继续i++,  当遇到第一个不等的字符 data[i]  则向后移动index (可以被覆盖的重复位置),然后用位置 i 的新字符data[i] 覆盖这个index 位置(第一个重复)的字符

public class RemoveDuplicates {

public static int removeDuplicates(int[] data){
if(data == null || data.length<1){
return 0;
}
int index = 0;
for(int i = 1; i < data.length ; i++){
if(data[index] != data[i]){
index++;
data[index] = data[i];
}
}
return index +1 ;
}
}

最后的index 标示新array的最后一个字符位置,问题是返回长度所以加1.

思考题,最后的Index之后的数组空间还剩余哪些垃圾元素?

另外一个题:如果允许重复两次如何处理?

/*
* 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 static int removeDuplicates2(int[] data){
if(data == null || data.length<1){
return 0;
}
int index = 0;
int dup = 0;
for(int i = 1; i < data.length ; i++){

if(data[index] != data[i]){
index++;
data[index] = data[i];
dup = 0;
}else {
dup ++;
if(dup <2){
index ++;
}
}
}
return index +1 ;

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