442. Find All Duplicates in an Array(C++)

来源:互联网 发布:混沌战域神兵进阶数据 编辑:程序博客网 时间:2024/06/11 14:19

原題

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]



解題思路

題目限制了不能使用額外的空間以後時間複雜度為O(n),所以不可以用額外的空間來記錄數字出現的次數以後用排序來確定次數。但是這題有一個特別的條件,就是數組裏的數字的最大值不會大於數組的容量,以及沒有負數以及零的出現。所以我們可以通過修改數組本身來記錄數字的出現次數。例如a[0]的絕對值為4,它就會把a[4-1]的值取負。這樣若再有一個值為4,會發現a[4-1]的值為負,這表明了前面已經有一個4的存在,我們就可以得知有兩個4。





代碼

#include <cmath>


class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        vector<int> result;
        
        if (nums.empty()) {
            return result;
        }
        
        for (int i = 0; i < nums.size(); i++) {
            int temp = abs(nums[i]) - 1;
            if (nums[temp] < 0) {
                result.push_back(temp+1);
            }
            else {
                nums[temp] = -nums[temp];
            }
        }
        
        return result;
    }
};





感想

其實我沒想出來怎麼做才能符合條件,這個是我看了別人的寫法學會的。






原创粉丝点击