目录结构
1.题目
给你一个整数数组 nums 。
如果一组数字 (i,j) 满足 nums[i] == nums[j] 且 i < j ,就可以认为这是一组 好数对 。
返回好数对的数目。
示例:
输入:nums = [1,2,3,1,1,3]
输出:4
解释:有 4 组好数对,分别是 (0,3), (0,4), (3,4), (2,5) ,下标从 0 开始
输入:nums = [1,1,1,1]
输出:6
解释:数组中的每组数字都是好数对
输入:nums = [1,2,3]
输出:0
提示:
1 <= nums.length <= 100
1 <= nums[i] <= 100
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-good-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
2.1暴力解
public class Solution1512 {
@Test
public void test1512() {
int[] nums = {1, 2, 3, 1, 1, 3};
assertEquals(4, numIdenticalPairs(nums));
}
public int numIdenticalPairs(int[] nums) {
int result = 0;
for (int i = 0; i < nums.length; ++i) {
for (int j = i + 1; j < nums.length; ++j) {
if (nums[i] == nums[j]) {
++result;
}
}
}
return result;
}
}
- 时间复杂度:
- 空间复杂度:
2.2组合数
n个相同的数能组成n(n-1)/2个题设好数对数目,故计数计算即可。
public class Solution1512 {
@Test
public void test1512() {
int[] nums = {1, 2, 3, 1, 1, 3};
assertEquals(4, numIdenticalPairs(nums));
}
public int numIdenticalPairs(int[] nums) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
int result = 0;
for (int key : map.keySet()) {
int v = map.get(key);
result += v * (v - 1) / 2;
}
return result;
}
}
- 时间复杂度:
- 空间复杂度: