您的位置:首页 > 其它

Leetcode018--删除数组中重复的元素

2016-12-22 10:14 375 查看
一、原题

  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 nums = 
[1,1,2]


  Your function should return length = 
2
, with the first two elements of nums being 
1
 and 
2
 respectively.
It doesn’t matter   what you leave beyond the new length. 

一、中文

给定一个单链表,和一个分组数K,每K个结点进行反转,如果最后的结点数不足K个就保持原来的链接顺序不变。 






三、举例

  给定一个排序的数组,将数组中的重复元素去掉,相同的只保留一个,并且返回数组新的元素个数,不要创建一个新的数组来保存结果。在常量时间内解决这个问题 


四、思路

这里提供了两种思路,第一种是找到重复的元素之后,使后面的数组向前移动,这样效率是比较低的

第二种思路是,找到不相同的元素和该元素的下一个元素进行交换,这样比较快一点。


五、程序

package LeetCode19;

public class LeetCode019{

//第一种方式,平移的方式,效率比较低
public static int skipDupAry(int num[]){
if(num == null || num.length < 1){
return 0;
}

int value = 0;

int length = num.length - 1;

for(int i = 0; i < length; i++){
int temp = num[i+1];

//如果后一个元素和前一个元素相等
if(temp == num[i]){
//将后面的元素左移一个
for(int j = i+1; j < length; j++){
num[j] = num[j+1];
if(j == length - 1){
num[j+1] = 0;
}
}
value++;
}
}
//System.out.println("value = "+value);

return num.length - value +1;
}

//第二种方式,通过元素交换的方式,效率高
public static int removeDuplicates(int[] A) {

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

int index = 0;//[0,index]只记录数组中出现的按从小到大的唯一一个数,已经排好序了
int next = 1;

// 算法思想:找index之后的比A[index]大的数,如是找到就移动到A[index+1]处,
// index移动到下一个位置,next移动到下一个位置,再找比A[index]大的数

while (next < A.length) {
//当没有找到不重复的元素的时候,一直移动next
while (next < A.length && A[index] == A[next] ) { // 找不等于数组中最
next++;
}

//找到了不相同的元素了,将next的值赋值给index+1的位置
if (next < A.length) {
index++;
A[index] = A[next];
next++;
}
}
return index + 1;
}

public static void main(String args[]){
int num[] = new int[]{1, 2, 2, 3, 3, 4, 5};

int k1 = skipDupAry(num);
for(int i = 0; i < k1; i++){
System.out.print(num[i]+" ");
}

//		int k = removeDuplicates(num);
//		for(int i = 0; i < k; i++){
//			System.out.print(num[i]+" ");
//		}

System.exit(0);
}

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