剑指offer_数组中重复的数字

题目描述:

  • 找出数组中重复的数字
  • 在一个长度为n的数组里的所有数字都在0~n-1的范围内
  • 数组中某些数字是重复的,但不知道有几个数字重复了,也不知道,每个数字重复
  • 了几次,找出数组中任意一个重复的数字,例如,输入长度为7的数组{2,3,1,0,2,5,3}
  • 那么对应的输出是重复的数字2 或者3
    三个思路:
    方法1 :把输入的数组排序,然后从排序后的数组中找到重复的数字,只需要遍历查找即可,
    // 排序一个长度为n 的数组的时间复杂度是O(nlogn)
    代码实现:
public static Set<Integer> repeat(int[] a) {
		// 这里返回Set是因为,Set 是无序的。
		Set<Integer> set = new HashSet<Integer>();
		Arrays.sort(a);// 对数组排序
		for (int i = 0; i < a.length - 1; i++) {
			if (a[i] == a[i + 1])
				set.add(a[i]);
		}
		return set;
	}

方法2: 方法2: 可以用哈希标来解决这个问题,从头到尾按顺序扫描数组的每一个数字,每扫描到一个数字的时候,
// 都去判断一下是否包含了这个数字,如果哈希表没有这个数字,就加入哈希标,如果哈希标
// 存在这个数字,就找到一个重复的数字

public static Set<Integer> repeat1(int[] a) {
		// 这里返回Set是因为,Set 是无序的。
		Set<Integer> set = new HashSet<Integer>();
		Set<Integer> set1 = new HashSet<Integer>();
		for (int i = 0; i < a.length; i++) {
			if (!set.contains(a[i])) {
				set.add(a[i]);
			} else {
				set1.add(a[i]);
			}
		}
		return set1;
	}

方法3: 用换位的方式去寻找这个集合数组
// 我们重排这个数组,从头到尾以此扫描这个数组中的每个数字,
// 当扫到下标是i 的数字的时候,首先比较这个数字m 是不是等于i
// 如果是,则接着扫面下一个数字,如果不是,则再拿他和第m个数字进行比较,如果和第m个数字相等
// 就找到了一个重复的数字

	public static Set<Integer> repeat2(int[] a) {
		// 这里返回Set是因为,Set 是无序的。

		Set<Integer> set1 = new HashSet<Integer>();
		for (int i = 0; i < a.length; i++) {
			if (a[i] != i) {
				if (a[i] == a[a[i]])
					set1.add(a[i]);
				else {
					int temp = a[i];
					a[i] = a[temp];
					a[temp] = temp;
				}
			}
		}
		return set1;
	}

测试代码:

public static void main(String[] args) {
		int[] a = { 1, 2, 2, 2, 4, 5, 5, 7, 8 };

		  Set<Integer> b = repeat(a); for (int c : b) { System.out.println(c); }
		  Set<Integer> repeat1 = repeat1(a); for (int i : repeat1) {
		  System.out.println(i); }
		 
		Set<Integer> repeat2 = repeat2(a);
		for (int i : repeat2) {
			System.out.println(i);
		}
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值