Created
July 2, 2019 16:14
-
-
Save yangpeng-chn/93e3f870fba90b57fcf60d75696d46a1 to your computer and use it in GitHub Desktop.
Cyclic sort
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
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