您的位置:首页 > Web前端

剑指offer_数组---数组中重复的数字

2017-08-26 11:21 274 查看

题目描述

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

解题思路

1,用额外的空间来给数组里的数字打标签,当发现重复标签的时候说明找到了

2,将数组里的数字放到和自己值相同的索引处,如果发现索引冲突,则说明找到了

代码实现

/**
*
*/
package 数组;

/**
* <p>
* Title:Duplicate
* </p>
* <p>
* Description:
* </p>
*
* @author 田茂林
* @data 2017年8月26日 上午10:03:34
*/
public class Duplicate {
// ===========================================================================使用辅助的boolean数组
public static boolean duplicate(int numbers[], int length, int[] duplication) {
if (numbers == null || length < 1) {
return false;
}
for (int i = 0; i < duplication.length; i++) { // 数组元素是否超限判断
if (numbers[i] < 0 || numbers[i] > length - 1) {
return false;
}
}
boolean[] flag = new boolean[length];
for (int i = 0; i < length; i++) {
flag[numbers[i]] = false; // 初始化所有数组元素都是false
}
for (int i = 0; i < length; i++) {
if (flag[numbers[i]] == true) { // 遇到之前修改过的,就说明遇到重复的了
duplication[0] = numbers[i];
return true;
}
flag[numbers[i]] = true; // 遇到元素就修改为true
}
return false;

}

// ===========================================================================不使用额外空间
public static boolean duplicateSuper(int numbers[], int length,
int[] duplication) {
if (numbers == null || length < 1) {
return false;
}
for (int i = 0; i < length; i++) {
if (numbers[i] < 0 || numbers[i] > length - 1) {
return false;
}
}
for (int i = 0; i < length; i++) {
while (numbers[i] != i) {
if (numbers[i] == numbers[numbers[i]]) {   //如果发现不同的索引处有相同的值,说明重复了
duplication[0] = numbers[i];
return true;
}
exchange(numbers, i, numbers[i]);      //把数字放到和自己值相同的索引处

}
}
return false;

}

public static void exchange(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;

}

public static void main(String[] args) {
int[] array = { 2, 3, 1, 0, 2, 5, 3 };
int[] duplication = new int[1];
System.out.println(duplicate(array, 7, duplication));

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: