0
点赞
收藏
分享

微信扫一扫

Day24 缺失的第一个正数

给你一个未排序的整数数组 nums ,请你找出其中没有出现的最小的正整数

https://leetcode-cn.com/problems/first-missing-positive/

示例1:

示例2:

示例3:

提示:

Java解法

package sj.shimmer.algorithm.ten_3;

/**
 * Created by SJ on 2021/2/17.
 */

class D24 {
    public static void main(String[] args) {
        System.out.println(firstMissingPositive(new int[]{1,2,0}));
        System.out.println(firstMissingPositive(new int[]{3,4,-1,1}));
        System.out.println(firstMissingPositive(new int[]{7,8,9,11,12}));
        System.out.println(firstMissingPositive(new int[]{1}));
    }
    public static int firstMissingPositive(int[] nums) {
        if (nums == null||nums.length==0) {
            return 1;
        }
        int[] n = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i]-1;//-1表示位置进行前移一位,0不为正数
            if (num>nums.length-1||num<0) {
                continue;
            }
            n[num] = ++n[num];
        }
        for (int i = 0; i < n.length; i++) {
            if (n[i]==0) {
                return i+1;
            }
        }
        return n.length+1;
    }
}

官方解

https://leetcode-cn.com/problems/first-missing-positive/solution/que-shi-de-di-yi-ge-zheng-shu-by-leetcode-solution/

角度算法都可以,但效率都没有特别好。。。

  1. 哈希表

    • 时间复杂度:O(N)
    • 空间复杂度:O(1)
  2. 置换

    • 时间复杂度:O(N)
    • 空间复杂度:O(1)
举报

相关推荐

0 条评论