【LeetCode】First Missing Positive

参考链接

http://blog.csdn.net/doc_sgl/article/details/12321271


题目描述

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.


题目分析


思路:交换数组元素,使得数组中第i位存放数值(i+1)。最后遍历数组,寻找第一个不符合此要求的元素,返回其下标。整个过程需要遍历两次数组,复杂度为O(n)。
以[3,4,-1,1]为例:




总结


代码示例


class Solution {
public:
    int firstMissingPositive(int A[], int n) {
    	
    //////////////////////////////	for(int i = 0;i<n;i++)
    	int i = 0;
    	while(i<n)
    	{
    		if(A[i] != i+1 && A[i]>0 && A[i]-1<n && A[i] != A[A[i]-1])
    			swap(A[i],A[A[i]-1]);
   			else
   				i++;
		}
		for(int i = 0;i<n;i++)
		 if(A[i] != i+1)	return i+1;
	 	
	 	return n+1;        
    }
};



推荐学习C++的资料

C++标准函数库
在线C++API查询

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章