题目描述:
一组无序的自然数集合,由0,1,2,,,,n的数字和一个的数字X组成,请从集合中找出这个重复的数字X。
例子:
输入:1 2 3 1 4
输出:1
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
String[] numstr = str.split(" ");
int[] nums = new int[numstr.length];
for(int i = 0; i < numstr.length; i ++) {
nums[i] = Integer.parseInt(numstr[i]);
}
getRepeateNum(nums);
}
public static void getRepeateNum( int[] num) {
int NumChange;
for(int index = 0; index < num.length; index++) {
boolean flag = true;
while(num[index] != index) {
if(num[index] == num[num[index]]) {
System.out.println(num[index]);
flag = false;
break;
} else {
NumChange = num[num[index]];
num[num[index]] = num[index];
num[index] = NumChange;
}
}
if (!flag){
break;
}
}
}
}