(Java)LeetCode-41. 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.


这道题蛮难啊,看起来比较简单,但是到下手的时候就不会了。

这道题的思路是以前没有接触过的,由于要求O(n)的时间复杂度,只能常数次遍历数组,所以就是将每个数n放到数组中序号为(n-1)的位置上,其中负数和大于数组长度的数不用管,没有他们的位置。重复的数也只放一次就好了,这样再遍历一遍之后,再从头开始遍历数组,当哪个位置上的数不是希望的,则该位置希望的数就是缺少的第一个正整数。如果全都是希望的数,那么所缺的就是数组长度加一的那个数。代码如下:


public class Solution {
    public int firstMissingPositive(int[] nums) {
		int len = nums.length;
		for(int i = 0; i < len;){
			if(nums[i] != i+1 && nums[i] > 0 && nums[i] <= len && nums[i] != nums[nums[i]-1] ){
				swap(i,nums[i]-1,nums);
			}
			else{
				i++;
			}
		}
		for(int i = 1; i <= len; i++){
			if(nums[i-1] != i){
				return i;
			}
		}
		return len+1;
    }
	
	private void swap(int i, int j, int[] nums) {
		// TODO Auto-generated method stub
		int temp = nums[i];
		nums[i] = nums[j];
		nums[j] = temp;
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值