首页 > 其他 > 详细

LeetCode1512-好数对的数目

时间:2020-11-29 11:46:38      阅读:23      评论:0      收藏:0      [点我收藏+]

 

非商业,LeetCode链接附上:

https://leetcode-cn.com/problems/number-of-good-pairs/

进入正题。

 

题目:

给你一个整数数组 nums 。

如果一组数字 (i,j) 满足 nums[i] == nums[j] 且 i < j ,就可以认为这是一组 好数对 。

返回好数对的数目。

 

示例:

示例 1:

输入:nums = [1,2,3,1,1,3]
输出:4
解释:有 4 组好数对,分别是 (0,3), (0,4), (3,4), (2,5) ,下标从 0 开始
示例 2:

输入:nums = [1,1,1,1]
输出:6
解释:数组中的每组数字都是好数对
示例 3:

输入:nums = [1,2,3]
输出:0
 

提示:

1 <= nums.length <= 100
1 <= nums[i] <= 100

  

代码实现:

//方法一 暴力法
public static int numIdenticalPairs(int[] nums) {

        int count = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] == nums[j]) {
                    count++;
                }
            }
        }

        return count;
}
//时间复杂度O(n^2),空间复杂度O(1)

//方法二 哈希表统计+组合计数
public int numIdenticalPairs(int[] nums) {

        Map<Integer, Integer> m = new HashMap<>();
        for(int num : nums) {
            m.put(num, m.getOrDefault(num, 0) + 1);
        }
        
        int ans = 0;
        for(Map.Entry<Integer, Integer> entry : m.entrySet()) {
            int v = entry.getValue();
            ans += v * (v - 1) / 2;
        }
        
        return ans;

}
//时间复杂度O(n),空间复杂度O(n)

//方法三 利用数组性质+提示条件
public int numIdenticalPairs(int[] nums) {

        int ans = 0;
        int[] temp = new int[100];

        for(int num : nums) {
            ans += temp[num - 1];
            temp[num - 1]++;
        }

        return ans;

}
//时间复杂度O(n),空间复杂度O(n)

 

分析:

三种方法,三种思维。

 

附注:

第三种详解:https://leetcode-cn.com/problems/number-of-good-pairs/solution/zhe-gu-ji-shi-wo-xie-zen-yao-duo-ti-yi-lai-zui-dua/

 

--End

 

LeetCode1512-好数对的数目

原文:https://www.cnblogs.com/heibingtai/p/14055659.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!