Created
August 6, 2020 11:32
-
-
Save dimitriye98/802eb3963b2ed0afe57c77b45e396aca to your computer and use it in GitHub Desktop.
Fast Find Duplicates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma GCC optimize("Ofast") | |
static auto _ = [] () { | |
ios_base::sync_with_stdio(false); | |
cin.tie(nullptr); | |
cout.tie(nullptr); | |
return 0; | |
}(); | |
class Solution { | |
public: | |
vector<int> findDuplicates(vector<int>& nums) { | |
vector<int> ret{}; | |
size_t i = 0; | |
while (i < nums.size()) { | |
if (nums[i] == i + 1) { | |
++i; | |
} else if (nums[i] == nums[nums[i] - 1]) { | |
ret.push_back(nums[i]); | |
++i; | |
} else { | |
if (nums[i] <= i) { | |
swap(nums[i], nums[nums[i] - 1]); | |
++i; | |
} else { | |
swap(nums[i], nums[nums[i] - 1]); | |
} | |
} | |
} | |
return ret; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment