您的位置:首页 > 其它

LeetCode力扣之First Missing Positive

2018-03-07 15:32 323 查看
Given an unsorted integer array, find the first missing positive integer.For example,
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));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: