[leetcode] 442. Find All Duplicates in an Array

Question:

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

Could you do it without extra space and in O(n) runtime?

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[2,3]

Solution:

思路類似於翻牌子,充分利用條件 1 ≤ a[i] ≤ n,即數組元素的範圍-1不會超出下標的範圍,那麼遇到遇到一個數,就把數字對應下標的那個牌子翻過來(取反),如果已經翻了過來,則說明此前已經遇到了這個數字,這個數字就是重複出現的那個。

class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        vector<int> ret;
        for (int i : nums)
            if (nums[abs(i)-1] < 0)
                ret.push_back(abs(i));
            else
                nums[abs(i)-1] *= -1;
        return ret;
    }
};
發佈了79 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章