LeetCode-First Missing Positive

Description:
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);
例如:

  • 输入为[3,4,-1,1],排序后为[-1,1,3,4],对应数组[-1,0,1,2,3,4]来说,最小的不在数组中的正整数为2;
  • 输入为[7,8,9,11,12],排序后为[7,8,9,11,12],对应数组[1,2,3,4,5,6,7,8,9,10,11,12]来说,最小的不在数组中的正整数为1;

解法:这道题要求空间复杂度为O(1),那么我们所能利用的就是数组本身的存储空间;因为要求的是最小的不在数组中的正整数,所以我们需要考虑的仅仅是正整数,而且这个数必定在[1,array.length+1]这个范围内;所以,我们只要找出数组中不在这个范围内的数字;因此,我们可以把对应的数字存储在相应的下标下,例如:nums[0] = 1, nums[1] = 2, nums[nums.length-1] = nums.length;之后,再遍历一次数组找出不在范围内的数字;

class Solution {
    public int firstMissingPositive(int[] nums) {
        if(nums.length == 0){
            return 1;
        }//the array is empty      
        for(int i=0; i<nums.length;){
            //withing the scope and the number at the subscript doesn't exist
            if(nums[i] > 0 && nums[i] <= nums.length && nums[nums[i]-1] != nums[i]){
                int temp = nums[i];
                nums[i] = nums[nums[i]-1];
                nums[temp-1] = temp;
            }
            else{
                i++;
            }
        }
        for(int i=0; i<nums.length; i++){
            if(nums[i] != i+1) return i+1;
        }
        return nums.length + 1;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值