首页 > 其他 > 详细

LeetCode 41:First Missing Positive

时间:2016-01-04 11:45:05      阅读:278      评论: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.

 //类似于桶排序,交换数组元素,使得数组中第i位存放数值(i+1);
 //最后遍历数组,寻找第一个不符合此要求的元素,返回其下标。整个过程需要遍历两次数组,复杂度为O(n)。
 class Solution {
 public:
	 int firstMissingPositive(vector<int>& nums) {
		 int n = nums.size();
		 for (int i = 0; i < n; ++i)
		 {
			 while (nums[i]>0 && nums[i] < n && nums[nums[i]-1] !=nums[i])
				 swap(nums[nums[i]-1], nums[i]);
		 }
		 for (int i= 0; i < n; ++i)
		 {
			 if (nums[i] != i + 1)
				 return i + 1;
		 }
		 return n + 1;
	 }
 };

技术分享

LeetCode 41:First Missing Positive

原文:http://blog.csdn.net/geekmanong/article/details/50454646

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