Leetcode 41. First Missing Positive

Leetcode 41. First Missing Positive

算法:

  1. Check if 1 is present in the array. If not, you’re done and 1 is the answer. If nums = [1], the answer is 2. Replace negative numbers, zeros, and numbers larger than n by 1s. 检查1是否存在,不存在返回1。如果1存在,且数组只有一个元素,则返回2。把所有0,负数,大于数组size的数设置为1。
  2. Walk along the array. Change the sign of a-th element if you meet number a. Be careful with duplicates : do sign change only once. Use index 0 to save an information about presence of number n since index n is not available. 如果遇到1,就把数组下标为1的元素设置为负数。 如果遇到2,就把数组下标为2的元素设置为负数。以此类推。
  3. Walk again along the array. Return the index of the first positive element. 返回第一个数组里正数的下标。
  4. If nums[0] > 0 return n. 下标为0的元素大于0,例如:返回n. [1,2,3,1] -> 返回4
  5. If on the previous step you didn’t find the positive element in nums, that means that the answer is n + 1. 如果所有元素都大于0,返回n+1。
class Solution {
  public int firstMissingPositive(int[] nums) {
    int n = nums.length;

    // Base case.
    int contains = 0;
    for (int i = 0; i < n; i++)
      if (nums[i] == 1) {
        contains++;
        break;
      }

    if (contains == 0)
      return 1;

    // nums = [1]
    if (n == 1)
      return 2;

    // Replace negative numbers, zeros,
    // and numbers larger than n by 1s.
    // After this convertion nums will contain 
    // only positive numbers.
    for (int i = 0; i < n; i++)
      if ((nums[i] <= 0) || (nums[i] > n))
        nums[i] = 1;

    // Use index as a hash key and number sign as a presence detector.
    // For example, if nums[1] is negative that means that number `1`
    // is present in the array. 
    // If nums[2] is positive - number 2 is missing.
    for (int i = 0; i < n; i++) {
      int a = Math.abs(nums[i]);
      // If you meet number a in the array - change the sign of a-th element.
      // Be careful with duplicates : do it only once.
      if (a == n)
        nums[0] = - Math.abs(nums[0]);
      else
        nums[a] = - Math.abs(nums[a]);
    }

    // Now the index of the first positive number 
    // is equal to first missing positive.
    for (int i = 1; i < n; i++) {
      if (nums[i] > 0)
        return i;
    }

    if (nums[0] > 0)
      return n;

    return n + 1;
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值