Skip to content

Instantly share code, notes, and snippets.

@si-yao
Created October 14, 2019 02:29
Show Gist options
  • Save si-yao/32e8a7d53406beb71dcf8b1bf25accf1 to your computer and use it in GitHub Desktop.
Save si-yao/32e8a7d53406beb71dcf8b1bf25accf1 to your computer and use it in GitHub Desktop.
class Solution {
public int firstMissingPositive(int[] nums) {
for (int i = 0; i < nums.length; ++i) {
if (nums[i] == i + 1) {
continue;
}
int n = nums[i];
nums[i] = -1;
while (n > 0 && n <= nums.length && nums[n - 1] != n) {
int t = nums[n - 1];
nums[n - 1] = n;
n = t;
}
}
for (int i = 0; i < nums.length; ++i) {
if (nums[i] != i + 1) {
return i + 1;
}
}
return nums.length + 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment