题目链接:2784. 检查数组是否是好的(简单)
算法原理:
解法:哈希表
1ms击败100.00%
时间复杂度O(N)
思路很简单,我们只需要保证两件事:1~n-1出现1次,且n出现两次
因此我们可以一次遍历:
①找最大值,也就是找到base数组的n是多少
②哈希表中对应出现次数+1
由于数据范围只有1~200,因此我们可以用数组代替哈希表
最后返回前检查是否满足1~n-1出现1次,且n出现两次即可
JAVA代码:
class Solution { //2784. 检查数组是否是好的 public boolean isGood(int[] nums) { int n=nums.length; int[] hash=new int[201]; int mx=0; for(int x:nums){ mx=Math.max(mx,x); hash[x]++; } for(int i=1;i<mx;i++) if(hash[i]!=1) return false; return hash[mx]==2; } }