ps:因为codeforces新的题都刷的差不多了,比赛也不是天天有,所以打算上leetcode补点知识,题单里会贴一些比较有意思(比较有技巧性)的题

难度大概在mid-hard(其实大部分是hard..)

 

缺失的第一个正数(类似于求数组的mex):将数组本身看成哈希表

leetcode 题单
class Solution {
    public int firstMissingPositive(int[] nums) {
        int n=nums.length,flag=0;
        for(int i=0;i<n;i++){
            if(nums[i]==1)flag=1;
        }
        if(flag!=1)return 1;//数组里没有1
        for(int i=0;i<n;i++){//把数组里[1,n]以外的数变为1
            if(nums[i]<=0 || nums[i]>n)nums[i]=1;
        }
        

        for(int i=0;i<n;i++){//用nums[i]的正负来表示i出现过没有
            int a=Math.abs(nums[i]);
            if(a==n)nums[0]=-Math.abs(nums[0]);
            else nums[a]=-Math.abs(nums[a]);
            
        }


        for(int i=1;i<n;i++){
            if(nums[i]>0)return i;
        }
        if(nums[0]>0)return n;
        return n+1;
    }
}
View Code

相关文章:

  • 2022-12-23
  • 2021-08-14
  • 2021-12-20
  • 2022-12-23
  • 2021-11-02
  • 2021-05-26
  • 2021-11-05
  • 2021-10-28
猜你喜欢
  • 2021-09-19
  • 2022-01-07
  • 2021-10-15
  • 2022-12-23
  • 2022-12-23
  • 2021-10-26
  • 2022-12-23
相关资源
相似解决方案