首页 > 其他 > 详细

41. First Missing Positive

时间:2020-02-16 20:45:29      阅读:54      评论:0      收藏:0      [点我收藏+]

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.

 

 1 class Solution {
 2     public void swap(int[] nums, int a, int b){
 3         int temp = nums[a];
 4         nums[a] = nums[b];
 5         nums[b] = temp;
 6     }
 7     public int firstMissingPositive(int[] nums) {
 8         int n = nums.length;
 9         int i = 0;
10         while (i < n) {
11             if (nums[i] > 0 && nums[i] <= n) {
12                 if (i != nums[i] - 1  
13                     && nums[i] != nums[nums[i] - 1]) {
14                     swap(nums, i, nums[i] - 1);
15                 } else {
16                     i++;
17                 }
18             } else {
19                 i++;
20             }
21         }
22         
23         int ans = -1;
24         for (i = 0; i < n; ++i) {
25             if (nums[i]  != i + 1) {
26                 ans = i + 1;
27                 
28                 break;
29             }
30         }
31         
32         return ans == -1 ? n + 1 : ans;
33     }
34 }

 

41. First Missing Positive

原文:https://www.cnblogs.com/hyxsolitude/p/12317667.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!