LeetCode !!! 41 . First Missing Number

41. First Missing Positive
Given an unsorted integer array nums, return the smallest missing positive integer.

You must implement an algorithm that runs in O(n) time and uses constant extra space.

 

Example 1:

Input: nums = [1,2,0]
Output: 3
Explanation: The numbers in the range [1,2] are all in the array.
Example 2:

Input: nums = [3,4,-1,1]
Output: 2
Explanation: 1 is in the array but 2 is missing.

思路

我觉得这道题需要注意到的点是 寻找最小缺失正数, 不含0.
这样一来,最理想的状态是 arr[i]=i+1
首先把数组 尽可能地 恢复成 上述的理想状态。然后,遍历一遍数组,查缺了哪一位。

public void swap(int[] nums, int i, int j){
        int t=nums[i];
        nums[i]=nums[j];
        nums[j]=t;
    }

      public int firstMissingPositive(int[] nums) {
          int n = nums.length; // nums[i]=i+1
          for(int i=0;i<n;i++){
          // 注意这里使用的是while, 因为存在下面这种情况
          // arr: 4  5  6
          // idx: 1  3  4
          // swap(1,3) 之后 
          // arr: 5  4  6
          // idx: 1  3  4       // 还需要 swap(1,4) 之后  
          //  退出循环时,达到理想状态 nums[nums[i]-1]==nums[i]
              while(nums[i]>0&&nums[i]<n&&nums[nums[i]-1]!=nums[i]){
                  swap(nums,i,nums[i]-1);
              }
          }// end for
        for(int i=0;i<n;i++){
            if(nums[i]!=i+1){
                return i+1;
            }
        }
        return n+1;
      }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值