leetcode 41 First Missing Positive ---java

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.

这道题求的是在一个乱序数组中缺少的第一个正数,要求时间复杂度o(n)空间复杂度为1。

先上代码

package leetcode;

public class firstMissingPositive {
	public int firstMissingPositive(int[] nums) {
		int len = nums.length;
		int i = 0;
		while( i<len){
			if( nums[i] == i+1 || nums[i]<0 || nums[i] > len+1)
				i++;
			else if( nums[i] != nums[nums[i]-1])
				swap(nums,i,nums[i]-1);
			else
				i++;
		}
		i = 0;
		while(i<len && nums[i] == i+1)
			i++;
		return i+1;
    }
	
	public void swap(int[] nums, int a,int b){
		int num = nums[a];
		nums[a] = nums[b];
		nums[b] = num;
	}
	/*
	 * 1.求第一个缺少的正数,想通思路很简单。
	 */
}

 这道题虽然是hard,难点就是在于时间和空间复杂度,但是算法并不困难。

就是将每一个在1-len之间的正数放在num[i]上,然后遍历一次,遇到的第一个不一样的数就是结果。

原文地址:https://www.cnblogs.com/xiaoba1203/p/5603828.html