leetcode_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.

思路:

做过find the duplicate number再来解决该问题就很简单了,虽然上述方法并不适合上一题,但是挺适合这一题的即将数组nums[i]中的数值都存储到index为nums[i]-1的位置上,不在位置为index处的值则为(index+1),返回即可。

代码:

public int firstMissingPositive(int[] nums) {
		if(nums==null||nums.length==0)
			return 1;
        int temp = 0;
		int i = 0,index=0;
		while (i < nums.length) {
			if (i + 1 != nums[i]) {
				index=nums[i]-1;
				if(index<0||index>=nums.length)
				{
				    i++;
				    continue;
				}
				if(nums[index]!=nums[i])
					swap(nums, i, index);
				else {
					i++;
				}
				//i = nums[i] - 1;
			} else
				i++;

		}
		for (i = 0; i < nums.length; i++) {
			if (i + 1 != nums[i]) {
				temp = i+1;
				break;
			}
		}
		if(i==nums.length)
			return nums[nums.length-1]+1;
		return temp;
	}

	public void swap(int[] nums, int index1, int index2) {
		int temp = nums[index1];
		nums[index1] = nums[index2];
		nums[index2] = temp;
	}


你可能感兴趣的:(leetcode_First Missing Positive)