leetCode同: https://leetcode-cn.com/problems/first-missing-positive/solution/que-shi-de-di-yi-ge-zheng-shu-by-doctording-4/
划分区域,内部交换
O(n)
O(1)
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main { public static Scanner sc = new Scanner(System.in); static void swap(int[] arr, int i, int j){ int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } public static void main(String[] args) { int n = sc.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++){ arr[i] = sc.nextInt(); } int l = 0; // [1, l] int r = n; // [r, n] // arr[l] - 1 位置 的值等于 arr[l],相当于 该位置值确定好了 // arr[l] 理论上要等于 l+1, 即 arr[l]-1 要等于 l; l位置的值要为 l+1 while (l < r) { if (arr[l] == l + 1) { l++; }else if(arr[l] < l+1 || arr[l] > r || arr[arr[l] - 1] == arr[l]){ arr[l] = arr[--r]; }else { swap(arr, l, arr[l] - 1); } } System.out.println(l+1); } } /* 4 -1 2 3 4 1 4 1 2 3 4 5 */