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;
        }
    }
  • 相关阅读:
    poj2679
    poj2709
    poj1521
    poj2054
    静脉曲张病案
    眩晕耳鸣病案
    声嘶治验
    甘露消毒丹治疗高热不退一例
    黄芩汤加减治疗腹痛一例
    自残症治愈案
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/10815320.html
Copyright © 2011-2022 走看看