zoukankan      html  css  js  c++  java
  • 41. First Missing Positive (JAVA)

    Given an unsorted integer array, find the smallest missing positive integer.

    Example 1:

    Input: [1,2,0]
    Output: 3
    

    Example 2:

    Input: [3,4,-1,1]
    Output: 2
    

    Example 3:

    Input: [7,8,9,11,12]
    Output: 1
    

    Note:

    Your algorithm should run in O(n) time and uses constant extra space.

    因为不能额外使用空间,所以不能用HashTable,利用原本的数组记录状态。将值为正整数的数字放到对应值-1的下标位置。

    注意无限循环:比如[1,1],所以nums[nums[i]-1]==nums[i]的情况要排除。

    class Solution {
        public int firstMissingPositive(int[] nums) {
            int tmp;
            int i = 0;
            while(i < nums.length){
                if(nums[i] < nums.length && nums[i] > 0 && nums[i] != i+1 && nums[nums[i]-1]!=nums[i]){
                    //put nums[i] at position of nums[i]-1
                    tmp = nums[i];
                    nums[i] = nums[tmp-1];
                    nums[tmp-1] = tmp;
                }
                else{
                    i++;
                }
            }
            
            for(i = 0; i < nums.length; i++){
                if(nums[i] != i+1) break;
            }
            return i+1;
        }
    }
  • 相关阅读:
    BZOJ 3744 Gty的妹子序列
    BZOJ 3872 Ant colony
    BZOJ 1087 互不侵犯
    BZOJ 1070 修车
    BZOJ 2654 tree
    BZOJ 3243 向量内积
    1003 NOIP 模拟赛Day2 城市建设
    CF865D Buy Low Sell High
    CF444A DZY Loves Physics
    Luogu 4310 绝世好题
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/10815320.html
Copyright © 2011-2022 走看看