• 《程序员代码面试指南》第八章 数组和矩阵问题 数组中未出现的最小正整数


    题目

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

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

    结果

  • 相关阅读:
    python--初识面向对象
    python--内置函数, 匿名函数
    P2249 【深基13.例1】查找
    P5143 攀爬者
    P1116 车厢重组
    P1059 明明的随机数
    P1152 欢乐的跳
    字符数组
    nth_element(取容器中的第n大值)
    费曼学习法
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/9016919.html
Copyright © 2020-2023  润新知