[leetcode] Remove Duplicates from Sorted Array

描述
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 ;
		
	}
	


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值