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;
        }
    }
  • 相关阅读:
    mysql的复制
    web页面请求历程
    django工作原理简介
    http协议
    路由器和交换机的区别
    OSI七层模型
    TCP/IP协议总结
    IO复用
    僵尸进程和孤儿进程
    java源代码如何打成jar包
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/10815320.html
Copyright © 2011-2022 走看看