【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查詢

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