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

    Question:https://leetcode.com/problems/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.


    分析:

    一般性的解法是利用 Bucket Sort, 声明一个 length 为 nums.length 的 boolean 数组 A。Sudo Code 如下:

     1 for(int i = 0; i < nums.length; i++):
     2     if(nums[i] <= 0 || nums[i] > nums.length): 
     3         continue
     4     else: 
     5         A[nums[i]-1] = true
     6 
     7 for(int i = 0; i < A.length; i++):
     8     if(A[i] != true):
     9         return (i+1)
    10 
    11 // Nums from 1 to (nums.length-1) have been in array nums, 
    12 // so firstMissingPositive is nums.length
    13 return nums.length  

    这里明显是需要 O(n) space, O(2n) runtime. 但是题目中要求 constant space。遇到这种题目,还有类似的 Binary Tree Traversal O(1) space solution, 一般性的思路都是采用利用 改变 parameter variable 中的 data structure 来实现求解,但是这样做会破坏原来的数据结构,如果要求原来的数据结构不变,那么处理得到result后,还需要将数据结构恢复。

    于是,Solution 如下:

     1 public int firstMissingPositive(int[] nums) {
     2     if(nums == null || nums.length == 0) {
     3         return 1;
     4     }
     5     
     6     for(int i = 0; i < nums.length; i++) {
     7         if(nums[i] <= 0 || nums[i] > nums.length) {
     8             continue;
     9         } else if(nums[i] != i + 1) {
    10             int tmp = nums[i];
    11             
    12             // Attention here !!! Otherewise, possible dead loop
    13             if(nums[tmp-1] == tmp) {
    14                 continue;
    15             }
    16             
    17             nums[i] = nums[tmp-1];
    18             nums[tmp-1] = tmp;
    19             i--;
    20         }
    21     }
    22     
    23     for(int i = 0; i < nums.length; i++) {
    24         if(nums[i] != i+1) {
    25             return i+1;
    26         }
    27     }
    28     
    29     return nums[nums.length-1]+1;
    30 }
  • 相关阅读:
    Best Time to Buy and Sell Stock III
    Valid Palindrome
    Longest Substring Without Repeating Characters
    Copy List with Random Pointer
    Add Two Numbers
    Recover Binary Search Tree
    Anagrams
    ZigZag Conversion
    Merge k Sorted Lists
    Distinct Subsequences
  • 原文地址:https://www.cnblogs.com/Phoenix-Fearless/p/5109087.html
Copyright © 2011-2022 走看看