LeetCode 41. First Missing Positive

原题链接在这里:https://leetcode.com/problems/first-missing-positive/

题目:

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.

题解:

两遍扫描,第一遍时swap nums[i] 和它对应的位置元素nums[nums[i]-1]. 为什么对应位置是nums[nums[i]-1]而不是nums[nums[i]]呢? 举个例子nums = [2,1,3], first missing positive 是 4. 若对应位置是nums[i]的话就会swap成[3,1,2], 就会return错误的值.

第二遍时找是否有 nums[i] != i+1的,若有就返回i+1.

若走到头还没有return, 说明first missing positive 是 nums.length+1.

Note: 第一遍扫描时 swap 的条件是 nums[i]-1>=0并且<nums.length, 如此nums[i]-1才有对应的位置;并且排除掉nums[i] == nums[nums[i]-1]情况,即两点已经相同,不需要swap, 否则陷入infinite loop. 做这类swap时注意对调是否相同,是否会造成infinite loop. 

i--是保证swap后 i 返回原位。

Time Complexity: O(n). Space: O(1).

AC Java:

 1 class Solution {
 2     public int firstMissingPositive(int[] nums) {
 3         if(nums == null){
 4             throw new IllegalArgumentException("Input array is null.");
 5         }
 6         
 7         for(int i = 0; i<nums.length; i++){
 8             if(nums[i]-1>=0 && nums[i]-1<nums.length && nums[i] != nums[nums[i]-1]){
 9                 swap(nums, i, nums[i]-1);
10                 i--;
11             }
12         }
13         
14         for(int i = 0; i<nums.length; i++){
15             if(nums[i] != i+1){
16                 return i+1;
17             }
18         }
19         
20         return nums.length+1;
21     }
22     
23     private void swap(int [] nums, int i, int j){
24         int temp = nums[i];
25         nums[i] = nums[j];
26         nums[j] = temp;
27     }
28 }

 类似Missing NumberFind the Duplicate Number.

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4881242.html