首页 > 其他 > 详细

Leetcode 41: First Missing Positive

时间:2018-01-22 10:20:47      阅读:164      评论:0      收藏:0      [点我收藏+]

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.

 

 1 public class Solution {
 2     public int FirstMissingPositive(int[] nums) {
 3         for (int i = 0; i < nums.Length; i++)
 4         {
 5             while (nums[i] > 0 && nums[i] <= nums.Length && nums[nums[i] - 1] != nums[i])
 6             {
 7                 var tmp = nums[nums[i] - 1];
 8                 nums[nums[i] - 1] = nums[i];
 9                 nums[i] = tmp;
10             }
11         }
12         
13         for (int i = 0; i < nums.Length; i++)
14         {
15             if (nums[i] != i + 1)
16             {
17                 return i + 1;
18             }
19         }
20         
21         return nums.Length + 1;
22     }
23 }

 

Leetcode 41: First Missing Positive

原文:https://www.cnblogs.com/liangmou/p/8327656.html

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