LeetCode 041.First Missing Positive

Given an unsorted integer array, find the smallest missing positive integer.

Example 1:

Input: [1,2,0]
Output: 3

Example 2:

Input: [3,4,-1,1]
Output: 2

Example 3:

Input: [7,8,9,11,12]
Output: 1

Note:

Your algorithm should run in O(n) time and uses constant extra space.

 

比较有趣的是题干要求时间复杂度O(n)并且只能使用O(1)的额外空间,这就意味着不能排序,不能用hashmap,也不能新建一张表来记录有过的点。

想了十分钟没想到办法,看了评论,才醒悟过来可以使用原数组的空间来作记录啊!

具体来说,遍历数组,一旦遇到大于0并且小于数组上限的值,就放到数组对应的位置当中去。在放到对应位置的同时,当然也要妥善处理好目标位置上的数字。并且在遍历过程中不能重复访问那些已经被换过,处在正确的位置上的数字,以保证即使有双层循环也一定是O(n)的时间。

下面是代码:

class Solution {
    public int firstMissingPositive(int[] nums) {
        int p = 0;
        for(p=0;p<nums.length;p++)
        {
            int temp =nums[p];
            while(temp>0 && temp<=nums.length && nums[temp-1]!=temp)
            {
            	int temp2 = nums[temp-1];
            	nums[temp-1] = temp;
            	temp = temp2;
            }
        }
        for(p=0;p<nums.length;p++)
        {
        	if(nums[p]!=p+1)
        		return p+1;
        }
        return nums.length+1;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值