【LeetCode刷题】1512. 好数对的数目

给你一个整数数组 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

===============================================================================================================================================================================================================================================================================================

分析:

法一:两层循环匹配

class Solution {
    public 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;
    }
}

 

法二:

官方给出的提示:Count how many times each number appears. If a number appears n times, then n * (n – 1) // 2 good pairs can be made with this number.

计算每个元素出现的次数。如果一个元素出现了n次,那么就有n*(n-1)/2个好数对。

加上题目给的限定条件:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100
class Solution {
    public int numIdenticalPairs(int[] nums) {
        int[] res=new int[101];                   //数组最大长度
        for(int i=0;i<nums.length;i++){
            res[nums[i]] = res[nums[i]]+1;        //统计每个元素出现的次数
        }

        int count = 0;
        for(int i=0;i<res.length;i++){
            count += res[i] * (res[i]-1) /2;
        }
        return count;
    }
}

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

贴一个解法:https://leetcode-cn.com/problems/number-of-good-pairs/solution/zhe-gu-ji-shi-wo-xie-zen-yao-duo-ti-yi-lai-zui-dua/

class Solution {
    public int numIdenticalPairs(int[] nums) {
        int ans = 0;
        //因为 1<= nums[i] <= 100  所以申请大小为100的数组
        //temp用来记录num的个数
        int[] temp = new int[100];
        /*
        从前面开始遍历nums
        假设nums = [1,1,1,1]
        第一遍
        temp是[0,0,0,0]
        ans+=0;
        temp[0]++;
        第二遍
        temp是[1,0,0,0]
        ans+=1;
        temp[0]++;
        第三遍
        temp=[2,0,0,0]
        ans+=2;
        temp[0]++;
        第四遍
        temp=[3,0,0,0]
        ans+=3;
        temp[0]++;
        */
        for (int num : nums) {
            /*
            这行代码可以写成
            ans+=temp[num - 1];
            temp[num - 1]++;
            */
            ans += temp[num - 1]++;
        }
        return ans;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值