不修改数组找出重复的数字

题目描述:在一个长度为n+1的数组里的所有数字都在1~n的范围内,所以数组中至少有一个数字重复。请找出数组中任意一个重复的数字,但不能修改输入的数组。例如,如果输入长度为8的数组{2,3,5,4,2,6,7},那么对应的输出是重复的数字2或者3。

注意:

1)考虑清楚是时间效率优先还是空间效率优先

2)找出一个重复数字还是找出所有的重复数字

3)输入的数字是否要做有效性判断

4)输入的数组是否可修改

思路:二分查找

代码:

public class getDuplicate {

	public static void main(String[] args) {

		int[] nums = {2,1,5,4,3,2,6,7};
		int count = getDuplication(nums, nums.length);
		System.out.println(count);
	}
	public static int getDuplication(int nums[], int length){
		if(nums == null || length <= 0)
			return -1;
		int start = 1, end = length - 1;
		while(start <= end){
			int mid = (end + start)>>1;
		    int count = countRange(nums, length, start, mid);
		    if(end == start){
		    	if(count > 1)
		    		return start;
		    	else
		    		break;
		    	
		    }
		    if(count > (mid - start + 1)){
		    	end = mid;
		    }
		    else 
		    	start = mid + 1;
		}
		return -1;
		
	}

	public static int countRange(int nums[], int length, int start, int end){
		if(nums == null)
			return 0;
		int count = 0;
		for(int i = 0; i < length; i++){
			if(nums[i] >= start && nums[i] <= end)
				count++;
		}
		return count;
		
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

甄臻924

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值