/**
* Problem: LeetCode 2784 - Check if Array is Good
* Difficulty: Easy
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public boolean isGood(int[] nums) {
int n = nums.length - 1;
if (n < 1) {
return false;
}
int[] count = new int[n + 1];
for (int num : nums) {
if (num < 1 || num > n) {
return false;
}
count[num]++;
}
// Each number from 1 to n - 1 must appear exactly once
for (int i = 1; i < n; i++) {
if (count[i] != 1) {
return false;
}
}
// The number n must appear exactly twice
return count[n] == 2;
}
}
"""
Problem: LeetCode 2784 - Check if Array is Good
Difficulty: Easy
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def isGood(self, nums: List[int]) -> bool:
n = len(nums) - 1
if n < 1:
return False
count = [0] * (n + 1)
for num in nums:
if num < 1 or num > n:
return False
count[num] += 1
# Each number from 1 to n - 1 must appear exactly once
for i in range(1, n):
if count[i] != 1:
return False
# The number n must appear exactly twice
return count[n] == 2
/**
* Problem: LeetCode 2784 - Check if Array is Good
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
using namespace std;
class Solution {
public:
bool isGood(vector<int>& nums) {
int n = nums.size() - 1;
if (n < 1) {
return false;
}
vector<int> count(n + 1, 0);
for (int num : nums) {
if (num < 1 || num > n) {
return false;
}
count[num]++;
}
// Each number from 1 to n - 1 must appear exactly once
for (int i = 1; i < n; i++) {
if (count[i] != 1) {
return false;
}
}
// The number n must appear exactly twice
return count[n] == 2;
}
};
/**
* Problem: LeetCode 2784 - Check if Array is Good
* Difficulty: Easy
* Language: JavaScript
* Author: CodeByTushu
*/
var isGood = function(nums) {
const n = nums.length - 1;
if (n < 1) {
return false;
}
const count = new Int32Array(n + 1);
for (const num of nums) {
if (num < 1 || num > n) {
return false;
}
count[num]++;
}
// Each number from 1 to n - 1 must appear exactly once
for (let i = 1; i < n; i++) {
if (count[i] !== 1) {
return false;
}
}
// The number n must appear exactly twice
return count[n] === 2;
};