1. 程式人生 > >leetcode +找到所有出現兩次的數字,標記。很巧妙

leetcode +找到所有出現兩次的數字,標記。很巧妙

點選開啟連結
class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        vector<int> result;
        int index;
        for (int i = 0;i<nums.size();i++) {
            index = abs(nums[i]) - 1;
           // cout<< nums[index]<<" "<<index+1<<endl;
            if (nums[index] > 0) {
                nums[index] = -nums[index];
            } else {
                result.push_back(index + 1);
            }
        }
        return result;
    }
};

int main()
{
    Solution s1;
    vector<int> tmp;
    tmp.push_back(4), tmp.push_back(3), tmp.push_back(2), tmp.push_back(7);
    tmp.push_back(8), tmp.push_back(2), tmp.push_back(3), tmp.push_back(1);
    s1.findDuplicates(tmp);
    return 0;
}