leetcode算法练习【41】缺失的第一个正数

所有题目源代码:Git地址

题目

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

 

示例 1:

输入: [1,2,0]
输出: 3
示例 2:

输入: [3,4,-1,1]
输出: 2
示例 3:

输入: [7,8,9,11,12]
输出: 1

方案:快排后遍历(快排复杂度高了,不行)

class Solution {
    public int firstMissingPositive(int[] nums) {
        Arrays.sort(nums);
        if(nums.length==0||nums[0]>1)return 1;
        int tmp=1;
        for(int i=0;i<nums.length;i++){
            if(nums[i]==tmp){tmp++;}
            else if(nums[i]>tmp) return tmp;

        }
        return nums[nums.length-1]<0?1: nums[nums.length-1]+1;
    }
}

方案2:构造Hash数组

  • 原理很简单,将相应的数放到相应的坐标上去,
class Solution {
        public int firstMissingPositive(int[] nums) {


            int len = nums.length-1;
            int res = 0;
            int tmp = 0;
            while (res <= len) {

                //表示在正确的位置上,不用替换
                if (nums[res] == res + 1) {
                    res++;
                }else{
                    tmp = nums[res];
                    //nums[tmp-1] == tmp? tmp位置的值已经为tmp 可以不用替换,不加的话,碰到两个一样的值会陷入死循环的情况
                    if (tmp>len+1||tmp<res+1||nums[tmp-1] == tmp){
                        nums[res]=nums[len--];
                    }else {
                        //需要吧tmp-1位置上的数交换到
                        nums[res] = nums[tmp-1];
                        nums[tmp-1] = tmp;
                    }
                }
            }
            return res+1;
        }
}
复杂度计算
  • 时间复杂度:快排O(nlogn)+遍历O(n)=O(nlogn);
    • 构造Hash数组:O(n)
  • 空间复杂度:O(1)
原创文章 179 获赞 270 访问量 34万+

猜你喜欢

转载自blog.csdn.net/symuamua/article/details/106110976