Skip to content

Instantly share code, notes, and snippets.

@yangpeng-chn
Created July 2, 2019 16:14
Show Gist options
  • Save yangpeng-chn/93e3f870fba90b57fcf60d75696d46a1 to your computer and use it in GitHub Desktop.
Save yangpeng-chn/93e3f870fba90b57fcf60d75696d46a1 to your computer and use it in GitHub Desktop.
Cyclic sort
int firstMissingPositive(vector<int>& nums) {
int n = nums.size();
for (int i = 0; i < n; ++i) {
while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) {
swap(nums[i], nums[nums[i] - 1]);
}
}
for (int i = 0; i < n; ++i) {
if (nums[i] != i + 1) return i + 1;
}
return n + 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment