检查数组是否是好的
难度:
标签:
题目描述
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 - 1
exactly once, plus two occurrences of n
). For example, base[1] = [1, 1]
and base[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.
Example 1:
Input: nums = [2, 1, 3] Output: false Explanation: Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. However, base[3] has four elements but array nums has three. Therefore, it can not be a permutation of base[3] = [1, 2, 3, 3]. So the answer is false.
Example 2:
Input: nums = [1, 3, 3, 2] Output: true Explanation: Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. It can be seen that nums is a permutation of base[3] = [1, 2, 3, 3] (by swapping the second and fourth elements in nums, we reach base[3]). Therefore, the answer is true.
Example 3:
Input: nums = [1, 1] Output: true Explanation: Since the maximum element of the array is 1, the only candidate n for which this array could be a permutation of base[n], is n = 1. It can be seen that nums is a permutation of base[1] = [1, 1]. Therefore, the answer is true.
Example 4:
Input: nums = [3, 4, 4, 1, 2, 1] Output: false Explanation: Since the maximum element of the array is 4, the only candidate n for which this array could be a permutation of base[n], is n = 4. However, base[4] has five elements but array nums has six. Therefore, it can not be a permutation of base[4] = [1, 2, 3, 4, 4]. So the answer is false.
Constraints:
1 <= nums.length <= 100
1 <= num[i] <= 200
代码结果
运行时间: 19 ms, 内存: 16.1 MB
/*
* 思路:
* 1. 使用 Java Stream 找到数组的最大值 max。
* 2. 如果数组长度不等于 max + 1,则返回 false。
* 3. 使用 Stream 生成 base 数组,包含 1 到 max,其中 max 重复两次。
* 4. 排序 nums 和 base 数组,比较两者是否相等。
*/
import java.util.Arrays;
import java.util.stream.IntStream;
public class Solution {
public boolean isGoodArray(int[] nums) {
int max = Arrays.stream(nums).max().orElse(0);
if (nums.length != max + 1) {
return false;
}
int[] base = IntStream.concat(IntStream.rangeClosed(1, max), IntStream.of(max)).toArray();
Arrays.sort(nums);
Arrays.sort(base);
return Arrays.equals(nums, base);
}
}
解释
方法:
题解通过使用Counter类来统计nums中每个元素的出现次数。首先,通过比较Counter的长度和nums的长度减一来判断是否只有一个元素重复出现。其次,题解检查nums中的最大元素是否等于nums的长度减一,这是因为如果nums是一个好数组,那么它将包含所有从1到n的元素,并且n出现两次。最后,题解检验重复元素(即最大元素)出现了两次。如果这三个条件都满足,则返回true,否则返回false。
时间复杂度:
O(n)
空间复杂度:
O(n)
代码细节讲解
🦆
在题解中,为什么需要检查`Counter(nums)`的长度是否等于`nums`长度减一?这与题目的要求有什么直接关系?
▷🦆
题解中提到,如果`max(nums)`不等于`nums`长度减一,返回false。能否解释为什么这个条件是判断数组是否是好的数组的关键?
▷🦆
题解使用了`Counter(nums)[len(nums)-1]==2`来确认重复的数字出现两次。这里为什么假设重复的元素必须是`nums`中的最大元素?
▷