劍指 數組中重複的數字

題目鏈接

遇到這種題,每次第一反應都是map啊,我太難了。

當然開個bool 做vis標記能做,這裏記錄討論裏一種沒想到的做法。

 

遇到過一次就加length,如果後面再遇到這個數,已經大於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) {
        if(length == 0) return false;
        for(int i = 0; i < length; i++) {
            int index = numbers[i];
            if(index >= length) {
                index -= length;
            }
            if(numbers[index] >= length) {
                *duplication = index;
                return true;
            }
            numbers[index] += length;
            
        }
        return false;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章