剑指offer50 数组中重复的数字(java)

版权声明:转载请标明出处哦 https://blog.csdn.net/easy_purple/article/details/84321237

题目

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

思路1

把当前序列当成是一个下标和下标对应值是相同的数组,遍历数组,判断当前位的值和下标是否相等

  • 若相等,则遍历下一位;
  • 若不等,则将当前位置i上的元素和a[i]位置上的元素比较:
    • 若它们相等,则找到了第一个相同的元素;
    • 若不等,则将它们两交换。换完之后a[i]位置上的值和它的下标是对应的,但i位置上的元素和下标并不一定对应;重复2的操作,直到当前位置i的值也为i,遍历下一位。

代码1

/**
 * 重复的数字交给a[0]
 */
public static boolean duplicate(int[] a, int length) {
	if (length == 0)
		return false;
	for (int i = 0; i < length; i++)
		if (a[i] > length)
			return false;
	for (int i = 0; i < length; i++) {
		while (i != a[i]) {
			if (a[i] == a[a[i]]) {
				a[0] = a[i];
				return true;
			}
			int tem = a[i];
			a[i] = a[tem];
			a[tem] = tem;
		}
	}
	return false;
}

思路2(很巧妙,思路源于作者

题目里写了数组里数字的范围保证在0 ~ n-1 之间,所以可以利用现有数组设置标志,当一个数字被访问过后,可以设置对应位上的数 + n,之后再遇到相同的数时,会发现对应位上的数已经大于等于n了,那么直接返回这个数即可

代码2

/**
 * 重复的数字交给a[0]
 */
public static boolean duplicate2(int[] a, int length) {
	if (length == 0)
		return false;
	for (int i = 0; i < length; i++)
		if (a[i] > length)
			return false;
	for (int i = 0; i < length; i++) {
		int index = a[i];
		if (index >= length)
			index -= length;
		if (a[index] >= length) {
			a[0] = index;
			return true;
		}
		a[index] += length;
	}
	return false;
}

猜你喜欢

转载自blog.csdn.net/easy_purple/article/details/84321237