Skip to content

Instantly share code, notes, and snippets.

@dimitriye98
Created August 6, 2020 11:32
Show Gist options
  • Save dimitriye98/802eb3963b2ed0afe57c77b45e396aca to your computer and use it in GitHub Desktop.
Save dimitriye98/802eb3963b2ed0afe57c77b45e396aca to your computer and use it in GitHub Desktop.
Fast Find Duplicates
#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