标签:public 案例 int and output integer 访问 gpo []
Given an unsorted integer array, find the smallest missing positive integer.
Note:
Your algorithm should run in O(n) time and uses constant extra space.
Input: [1,2,0]
Output: 3
Input: [3,4,-1,1]
Output: 2
Input: [7,8,9,11,12]
Output: 1
从左往右遍历每一个元素
class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.length, index, i = 0;
while(i < n){
if((index = nums[i]) <= 0 || nums[i] > n || nums[index - 1] == index){
i++;
}
else{
nums[i] = nums[index - 1];
nums[index - 1] = index;
}
}
for(i = 0; i < n && nums[i] == i + 1; i++);
return i + 1;
}
}
标签:public 案例 int and output integer 访问 gpo []
原文地址:https://www.cnblogs.com/echie/p/9592060.html