zoukankan      html  css  js  c++  java
  • LeetCode--041--缺失的第一个整数(java)

    给定一个未排序的整数数组,找出其中没有出现的最小的正整数。

    示例 1:

    输入: [1,2,0]
    输出: 3
    

    示例 2:

    输入: [3,4,-1,1]
    输出: 2
    

    示例 3:

    输入: [7,8,9,11,12]
    输出: 1
    

    说明:

    你的算法的时间复杂度应为O(n),并且只能使用常数级别的空间。

    思路:

    case1:length == 0                                                       return 1

    case2:length == 1  case2.1    [-1] [-....] [0] [2] [...]       return 1    

                                   case2.2    [1]                                return 2

    case3: length >1  跳过负数   case3.1  (nums[i] - nums[i-1] > 1) && (nums[i] > 1)                             [-1,2,3] or [-1,3,100]        return 1

                                                  case3.2 (nums[i] - nums[i-1] > 1) && (nums[i] - nums[i-1] < nums[i])  [-1,1,3]                             return nums[i-1] + 1

    case4: length > 1  i走到了最后一个 [1,2,3]                                                                                                                                return nums[nums.length -1 ] + 1  

    case5:length > 1   全为负数                                                                                                                                                       return 1

     1 class Solution {
     2     public int firstMissingPositive(int[] nums) {
     3         if(nums.length == 0 || nums == null) return 1;
     4         Arrays.sort(nums);
     5         if(nums.length == 1){
     6             if(nums[0] < 1 || nums[0] > 1){//[-1]  [2]
     7                 return 1;
     8             }else{
     9                 return 2;//[1]
    10             }
    11         }
    12         if(nums[0] > 1) return 1;
    13         for(int i = 1;i < nums.length;i++){
    14             if(nums[i] < 0)continue;
    15             if(nums[i] - nums[i-1] > 1 && nums[i] - nums[i-1] < nums[i]){//跳过[-1,2,3]
    16                 return nums[i - 1] + 1;
    17             }else if(nums[i] - nums[i-1] > 1 && nums[i] > 1) return 1;//[-1,2,3]
    18             if(i == nums.length - 1){
    19                 return nums[i] + 1;
    20             }
    21         }
    22         return 1;
    23     }
    24 }

    2019-05-01 21:11:23

  • 相关阅读:
    json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
    Java中时间与时间戳的转换
    python爬取网页数据
    selenium爬取网页内容知识点总结(代码均亲测可用)
    【LeetCode 5】 最长回文子串
    【LeetCode 4】寻找两个有序数组的中位数
    【LeetCode 3】无重复字符的最长子串
    【LeetCode 1】两数之和
    【LeetCode 2】两数相加
    【3-4】数字三角形问题
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/10800789.html
Copyright © 2011-2022 走看看