Leetcode __1512. 好数对的数目

问题描述

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

解题思路

第一反应就是最底层的方法,全都对比一遍,一样的就记录一次

实现

class Solution {
    public int numIdenticalPairs(int[] nums) {
        int len = nums.length;
        int res=0;
        for(int i=0;i<len;i++){
            for(int j=i+1;j<len;j++){
                if(j<len&&nums[i]==nums[j]){
                    res ++;
                }
            }
        }
        return res;
    }
}

对比

时间复杂度 n2

他人实现

class Solution {
    public int numIdenticalPairs(int[] nums) {
        int ans=0;
        int[] temp=new int[100];
        for(int num:nums){
            ans +=temp[num-1]++;
        }
        return ans;
    }
}

解析过程梳理:
根据给的示例,我们可以看出以下数学规律
在这里插入图片描述
因为提示中有
1 <= nums.length <= 100
1 <= nums[i] <= 100
所以 int[] temp=new int[100];
其中temp数组下标0、1、2、3…+1,也就是num中数字对应的位置
temp数组的value值就是num[i]数字的个数,这样把num数组的数据重新整理规整,得到temp数组,在根据序列公式求和,每2位取一次求值。

根据以上逻辑,再看实现代码
ans=ans+temp[num - 1];//总个数=每次增加个数相加
(如3的话,就是1+2)
temp[num - 1]++; //每出现一次相同的数字,计数+1

感慨

实在是太巧妙了,不禁感慨,大神果然是大神

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值