好数对的数目
难度:
标签:
题目描述
代码结果
运行时间: 19 ms, 内存: 15.9 MB
/*
* Approach:
* We can use Java Streams to solve this problem in a more functional way.
* We'll use a combination of IntStream and flatMap to generate all pairs of indices (i, j) where i < j.
* Then, we'll filter these pairs to find the good pairs where nums[i] == nums[j].
* Finally, we'll count the number of such pairs.
*/
import java.util.stream.IntStream;
public class GoodPairsStream {
public static int numIdenticalPairs(int[] nums) {
return (int) IntStream.range(0, nums.length)
.flatMap(i -> IntStream.range(i + 1, nums.length)
.filter(j -> nums[i] == nums[j]))
.count();
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 1, 1, 3};
System.out.println(numIdenticalPairs(nums)); // Output: 4
}
}
解释
方法:
这个题解采用了暴力法的思路。通过两层循环遍历数组,外层循环选取基准元素,内层循环查找之后的元素中与基准元素相同的元素。每当发现相同元素时,计数器增加,最终返回计数器的值作为结果。
时间复杂度:
O(n^2)
空间复杂度:
O(1)
代码细节讲解
🦆
为什么在解决这个问题时选择使用暴力法而不是哈希表或其他更高效的数据结构?
▷🦆
在函数中,`ans` 是如何确保不会重复计算相同的好数对?
▷🦆
在暴力法中,如果数组长度非常大,比如接近100,这种方法的性能表现如何?是否会有性能瓶颈?
▷🦆
在这个算法中,是否有可能通过提前终止内层循环来优化性能?
▷