[LeetCode] 1512. Number of Good Pairs
Given an array of integers nums, return the number of good pairs.
A pair (i, j) is called good if nums[i] == nums[j] and i < j.
Example 1:
Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
Example 2:
Input: nums = [1,1,1,1]
Output: 6
Explanation: Each pair in the array are good.
Example 3:
Input: nums = [1,2,3]
Output: 0
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100
好数对的数目。
给你一个整数数组 nums 。如果一组数字 (i,j) 满足 nums[i] == nums[j] 且 i < j ,就可以认为这是一组 好数对 。
返回好数对的数目。
思路一 - 暴力解
暴力解很好想,就是类似于 two sum 一样的两层 for 循环。由于数据量不是很大,这个思路是不超时的。
复杂度
时间O(n^2)
空间O(1)
代码
Java实现
class Solution { public int numIdenticalPairs(int[] nums) { // corner case if (nums == null || nums.length == 0) { return 0; } // normal case int res = 0; for (int i = 0; i < nums.length - 1; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] == nums[j]) { res++; } } } return res; } }
思路二 - hashmap
优化的思路是用 hashmap。每遇到一个数字,先去 hashmap 里看他是否存在,如果存在,拿到存在的次数,比如某个数字 X 之前 2 次,那么当我们第 3 次遇到他的时候,就往结果累加 2,因为当前这个 X 可以和之前两次 X 分别配对。
复杂度
时间O(n)
空间O(n)
代码
Java实现
class Solution { public int numIdenticalPairs(int[] nums) { int res = 0; HashMap<Integer, Integer> map = new HashMap<>(); for (int num : nums) { int count = map.getOrDefault(num, 0); res += count; map.put(num, count + 1); } return res; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具