剑指offer-question3-数组中重复的数字
题目:找出数组中的重复的数字
在一个长度为n的数组里的所有数字都在0~n-1的范围内。数组中的某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
1 package question3; 2 3 import java.util.Scanner; 4 5 public class Solution { 6 public static void main(String[] args) { 7 //int numbers[] = {3,1,2,5,2,5,3}; 8 int numbers[] = new int[7]; 9 Scanner scan = new Scanner(System.in); 10 11 for(int i = 0; i < numbers.length; i++) { 12 System.out.print("请输入第" + (i+1) + "个数字:"); 13 numbers[i] = scan.nextInt(); 14 } 15 16 int length = numbers.length; 17 //System.out.println("length"+length); 18 int duplication = 0; 19 int dup[] = new int[7]; 20 for(int i = 0; i < length; i++){ 21 if (numbers[i] < 0 || numbers[i] > length-1){ 22 System.out.println("数组非法"); 23 } 24 } 25 for(int i = 0; i < length; i++){ 26 while(numbers[i] != i){ 27 if(numbers[i] == numbers[numbers[i]]){ 28 duplication += 1; 29 dup[duplication-1] = numbers[i]; 30 31 System.out.println("当前有"+duplication+"个重复数字"); 32 break; 33 } 34 //System.out.println("test"+i); 35 //交换第i个位置的数和第i个位置数字为下标那个位置的数 36 int temp = numbers[i]; 37 numbers[i] = numbers[temp]; 38 numbers[temp] = temp; 39 40 } 41 } 42 System.out.println("扫描完成"); 43 System.out.print("重复数字为"); 44 for(int i = 0; i < dup.length; i++){ 45 if(dup[i] != 0) 46 { 47 System.out.print(dup[i]); 48 49 } 50 } 51 } 52 }
运行结果: