题目
数组中未出现的最小正整数
java代码
package com.lizhouwei.chapter8;
/**
* @Description: 数组中未出现的最小正整数
* @Author: lizhouwei
* @CreateDate: 2018/5/9 21:44
* @Modify by:
* @ModifyDate:
*/
public class Chapter8_25 {
public int missNum(int[] arr) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
if (arr[left] == left + 1) {
left++;
} else if (arr[left] <= left || arr[left] > right || arr[left] == arr[arr[left] - 1]) {
arr[left] = arr[right--];
} else {
swap(arr, left, arr[left] - 1);
}
}
return left + 1;
}
public void swap(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
//测试
public static void main(String[] args) {
Chapter8_25 chapter = new Chapter8_25();
int[] arr = {-1, 2, 3, 4};
int res = chapter.missNum(arr);
System.out.print("数组{-1, 2, 3, 4}中未出现的最小正整数: " + res);
}
}
结果