1. 程式人生 > >【劍指Offer】陣列中重複的數字

【劍指Offer】陣列中重複的數字

題目連結

題目描述

在一個長度為n的數組裡的所有數字都在0到n-1的範圍內。 陣列中某些數字是重複的,但不知道有幾個數字是重複的。也不知道每個數字重複幾次。請找出陣列中任意一個重複的數字。 例如,如果輸入長度為7的陣列{2,3,1,0,2,5,3},那麼對應的輸出是第一個重複的數字2。

分析:

1. 使用訪問標記陣列vis,初始化為false,第一次出現true的即為重複數字

class Solution {
public:
    // Parameters:
    //        numbers:     an array of integers
    //        length:      the length of array numbers
    //        duplication: (Output) the duplicated number in the array number
    // Return value:       true if the input is valid, and there are some duplications in the array number
    //                     otherwise false
    bool duplicate(int numbers[], int length, int* duplication) {
        bool vis[length];
        for(int i=0; i<length; i++){
            vis[i]=0;
        }
        for(int i=0; i<length; i++){
            if(vis[numbers[i]]){
                duplication[0] = numbers[i];
                return true;
            }
            vis[numbers[i]]=1;
        }
        return false;
    }
};

2. 通過判斷數值是否越界(>=length)

class Solution {
public:
    // Parameters:
    //        numbers:     an array of integers
    //        length:      the length of array numbers
    //        duplication: (Output) the duplicated number in the array number
    // Return value:       true if the input is valid, and there are some duplications in the array number
    //                     otherwise false
    bool duplicate(int numbers[], int length, int* duplication) {
        for(int i=0; i<length; i++){
            int index=numbers[i]%length;
            if(numbers[index]>=length){
                duplication[0]=index;
                return true;
            }
            numbers[index]+=length;
        }
        return false;
    }
};