查找数组中的重复数字(剑指office)

1、题目要求

在一个长度为n的数组nums里的所有数字都在0~n-1的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数组重复了几次。请找出数组中任意一个重复数字。

 输入: [2,3,1,0,2,5,3]
 输出:23

2、解题思路

方法一

Java我们可以通过Hash表来实现,再用循环去将数组中的元素添加到Hash表中,当重复数字出现第二次添加的时候,add(num)返回的就会是false,这是我们就可以将重复值返回回去。

方法二

第二种方法就是通过交换下标的方式来实现,也是比较常用的方式。

3、代码实现

方法一

public static void main(String[] args) {
		int[] sums = {2,3,1,0,2,5,3};
		int x = new demo_1().HashMethod(sums);
		System.out.println(x);   //输出: 2
	}
/**
	 * 方法一      使用Hash表   
	 *
	 */ 
	public int HashMethod(int[] nums) {
		int res = -1;
		Set<Integer> set = new HashSet<Integer>();
		for(int num : nums){
			if(!set.add(num)) {
				res = num;
				break;
			}
		}
		return res;
	}
方法二
public static void main(String[] args) {
	        ArrayRechecking aim = new ArrayRechecking();
	        int[] numbers={5,1,2,3,2,1,4};
	        int length=7;
	        int[] duplication=new int[1];
	        boolean aa = aim.ArrayIndexMethod(numbers, length, duplication);
	        System.out.println(aa + " "+ duplication[0]);
	    }

class ArrayRechecking{
		public boolean ArrayIndexMethod(int[] nums,int length,int[] Dvalue) {
			//  判断数组和长度是否为空
			if(nums == null|| length<=0) {
				return false;
			}
			//  排除不符合题意的部分
			for(int i=0; i<length;i++) {
				if(nums[i]<0 || nums[i]>=length) {
					return false;
				}
			}
			for(int i=0; i<length;i++) {
				while(nums[i] != i) {  
					if(nums[i] == nums[nums[i]]) { // true说明有重复
						Dvalue[0] = nums[i];	// 将重复值赋给数组存储
						return true;
					}
					int temp = nums[i];
					nums[i] = nums[temp];
					nums[temp] = temp;
				}
			}
			return false;
		}
	}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值