Code Interview Guide for Programmers Chapter 8 Arrays and Matrix Questions Smallest positive integer not present in an array

topic

数组中未出现的最小正整数

java code

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);
    }
}

result

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326673445&siteId=291194637