
这种题目直接得双重循环对吧!
然后发现了一个大神,代码如下,真的是思路清晰!
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;
}
}
作者:f1oisVo7a9
链接:https://leetcode-cn.com/problems/number-of-good-pairs/solution/zhe-gu-ji-shi-wo-xie-zen-yao-duo-ti-yi-lai-zui-dua/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
有一个点就是在ans+= temp[num-1]++这里,我一开始被自己绕进去了,为什么要重复加不是会错吗! 突然忘了3个数的好对数是1+2,需要重复加,因此可以理解成从后向前加的过程~