LeetCode力扣之First Missing Positive
2018-03-07 15:32
323 查看
Given an unsorted integer array, find the first missing positive integer.For example,
Given
and
* Created by lxw, liwei4939@126.com on 2018/3/7.
*/
public class L041_First_Missing_Positive {
public int missNum(int[] arr){
int left = 0;
int right = arr.length;
while (left < right){
if (arr[left] == left + 1){
left ++;
} else if (arr[left] <= left || arr[left] > right ||
arr[arr[left] - 1] == arr[left]){
arr[left] = arr[--right];
} else {
swap(arr, left, arr[left] - 1);
}
}
return left + 1;
}
void swap(int[] arr, int left, int right){
if(left != right){
arr[left] ^= arr[right];
arr[right] ^= arr[left];
arr[left] ^= arr[right];
}
}
public static void main(String[] args){
L041_First_Missing_Positive tmp = new L041_First_Missing_Positive();
int[] arr = new int[]{3, 4, -1, 2};
System.out.println(tmp.missNum(arr));
}
}
Given
[1,2,0]return
3,
and
[3,4,-1,1]return
2.Your algorithm should run in O(n) time and uses constant space./**
* Created by lxw, liwei4939@126.com on 2018/3/7.
*/
public class L041_First_Missing_Positive {
public int missNum(int[] arr){
int left = 0;
int right = arr.length;
while (left < right){
if (arr[left] == left + 1){
left ++;
} else if (arr[left] <= left || arr[left] > right ||
arr[arr[left] - 1] == arr[left]){
arr[left] = arr[--right];
} else {
swap(arr, left, arr[left] - 1);
}
}
return left + 1;
}
void swap(int[] arr, int left, int right){
if(left != right){
arr[left] ^= arr[right];
arr[right] ^= arr[left];
arr[left] ^= arr[right];
}
}
public static void main(String[] args){
L041_First_Missing_Positive tmp = new L041_First_Missing_Positive();
int[] arr = new int[]{3, 4, -1, 2};
System.out.println(tmp.missNum(arr));
}
}
相关文章推荐
- Leetcode220: First Missing Positive
- [LeetCode] First Missing Positive
- LeetCode First Missing Positive
- leetcode:First Missing Positive 【Java】
- 开始刷leetcode day20:First Missing Positive
- [LeetCode] First Missing Positive
- LEETCODE: First Missing Positive
- LeetCode(41) First Missing Positive
- LeetCode 41 First Missing Positive
- Leetcode First Missing Positive
- (LeetCode 41)First Missing Positive
- leetcode——41——First Missing Positive
- LeetCode 41 First Missing Positive
- leetcode || 41、First Missing Positive 问题
- leetcode做题总结,题目First Missing Positive 2012/03/08
- Leetcode--First Missing Positive
- leetcode — first-missing-positive
- [LeetCode(Q41)] First Missing Positive (乱序数组中寻找第一个未出现的正整数)
- [Leetcode]First Missing Positive
- leetcode First Missing Positive