天天看點

劍指offer 49:數組中重複的數字

題目描述

在一個長度為n的數組裡的所有數字都在0到n-1的範圍内。

數組中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出數組中任意一個重複的數字。

例如,如果輸入長度為7的數組{2,3,1,0,2,5,3},那麼對應的輸出是第一個重複的數字2

思路:

  1. 第一眼就覺得可以用map來做,隻要重複的就能得到key,但是這樣做空間時間太複雜,放棄了
  2. 然後想到利用map原理,key-value形式,key為數組的值,value就拿boolean,剛出現的就給true,發現已經為true說明之前出現過了,傳回即可
public class Solution {
    // Parameters:
    //    numbers:     an array of integers
    //    length:      the length of array numbers
    //    duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;
    //                  Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
    //    這裡要特别注意~傳回任意重複的一個,指派duplication[0]
    // Return value:       true if the input is valid, and there are some duplications in the array number
    //                     otherwise false
    public boolean duplicate(int numbers[],int length,int [] duplication) {
          boolean[] k=new boolean[length];
          for (int i = 0; i < k.length; i++) {   //把numbers每個值加進以boolean形式存進flag
            if (k[numbers[i]] == true) {
                duplication[0] = numbers[i];     //判斷到重複元素
                return true;
            }
            k[numbers[i]] = true;        //用value當作下标,boolean當作value
          }
        return false;
    }
}