/** 題目java
* 在一個長度爲n的數組裏的全部數字都在0到n-1的範圍內。數組
* 數組中某些數字是重複的,但不知道有幾個數字重複了,也不知道每一個數字重複了幾回。dom
* 請找出數組中任意一個重複的數字。例如,若是輸入長度爲7的數組{2, 3, 1, 0, 2, 5, 3},那麼對應的輸出是重複的數字2或者3。索引
*/rem
/**思路:class
*一、讓用戶輸入指定數組長度,而後準備數組數據(不考慮用戶輸入數據非法的狀況)import
*二、經過set去重數組,而後兩個數組想減,就得出一個只包含重複數字的數組;(注意這個數組裏依舊可能存在數據重複狀況,因此須要繼續去重)隨機數
*三、輸出List
*/im
import java.util.*;
public class Demo {
public static void main ( String[] args ) {
//------------------------------------------前期準備工做-------------------------------------------------------
//輸入數組的長度;
Scanner sc =new Scanner(System.in);
System.out.print("請輸入取值範圍(0~n):"+"\t");
int n = sc.nextInt ( );
//題目要求的數組
ArrayList<Integer> arr =new ArrayList<> ( );
//去重數組
HashSet< Integer > mset = new HashSet<> ( );
Random ran=new Random ( );
//隨機n次,產生n個數,存入數組中
for ( int i = 0; i <n ; i++ ) {
//產生一個0~n-1之間的隨機數,存入數組
int j = ran.nextInt ( n );
arr.add (j);
mset.add ( j );
}
System.out.println("------------------------[ 原始數據 ]------------------------");
System.out.println ("隨機數組值爲:"+arr);
System.out.println ("去重參考值爲:"+mset);
//------------------------------------------數據操做-------------------------------------------------------
//這時候,獲得了一個符合題目要求的數組;和一個沒有重複的set集合 if(arr.size ()<=0 ||arr==null){ System.out.println ("無效數組!" ); } if(arr.size ()==mset.size ()){ System.out.println ("數組中無重複數字!" ); }else{ //有重複數字,重複的數組爲:arr數組減去無重複數組mset for ( Integer integer : mset ) { //獲得該數字再arr數組中第一次的索引,刪除 int i = arr.indexOf ( integer ); arr.remove ( i ); } //再去重 HashSet< Integer >list = new HashSet<> ( ); for ( Integer i : arr ) { list.add ( i ); } //重複數字爲: System.out.println ("重複的值爲 : "+list ); } } }