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

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

    For example,
    Given [1,2,0] return 3,
    and [3,4,-1,1] return 2.

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

    Similar: 287. Find the Duplicate Number

    268. Missing Number

     1 public class Solution {
     2     public int firstMissingPositive(int[] nums) {
     3         if (nums.length == 0) return 1;
     4         
     5         int n = nums.length;
     6         int i = 0;
     7         while (i < n) {
     8             if (nums[i] > 0 && nums[i] < n && nums[i] != i && nums[nums[i]] != nums[i]) { // in case duplicate as [1,1]
     9                 int tmp = nums[nums[i]];
    10                 nums[nums[i]] = nums[i];
    11                 nums[i] = tmp;
    12             } else {
    13                 i++;
    14             }
    15         }
    16         
    17         i = 1;
    18         while(i < n) {
    19             if (nums[i] != i) {
    20                 return i;
    21             }
    22             i++;
    23         }
    24         return nums[0] == n ? n+1 : n;
    25     }
    26 }
  • 相关阅读:
    HTML的<head>中的内容总结
    毕业设计
    win7中protel99添加元件库
    E题
    D 题
    C 题 KMP中next[]问题
    B题 Sort the Array
    A题
    CSU1350 To Add which?
    CodeForce 448C 木片填涂问题
  • 原文地址:https://www.cnblogs.com/joycelee/p/5411955.html
Copyright © 2011-2022 走看看