[LeetCode] Check if Array is Good

2784. Check if Array is Good

You are given an integer array nums. We consider an array good if it is a permutation of an array base[n].

base[n] = [1, 2, ..., n - 1, n, n](in other words, it is an array of length n + 1 which contains 1 to n - 1exactly once, plus two occurrences of n). For example, base[1] = [1, 1] andbase[3] = [1, 2, 3, 3].

Return true if the given array is good, otherwise return false.

Note: A permutation of integers represents an arrangement of these numbers.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
bool isGood(vector<int>& nums) {
sort(begin(nums), end(nums));
if(nums.size() == 1) return false;
for(int i = 0; i < nums.size() - 1; i++) {
if(nums[i] != i + 1) return false;
}
if(nums.back() != nums[nums.size() - 2]) return false;
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/22/PS/LeetCode/check-if-array-is-good/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.