1512. Number of Good Pairs
Lc-1512
categories: [LeetCode]
tags: [Array, HashTable,Math,easy]
1512. Number of Good Pairs
題目大意:
給定一個陣列nums, 好數對的定義是如果nums[i] == nums[j]
並且 i < j, 要求返回好數對的數量
解題思路:
根據題意我們發現當陣列中第一次出現元素 k, 我們將其放在map當中,
並讓其value=1,接下來繼續遍歷陣列, 後面再出現元素k,其必將滿足
nums[i] == nums[j] && i < j, 後面再出現一個相同元素k,
就說明我們已經找到一對好數對了,同時在map中的該元素的value上加1
當第三次再出現該元素,因為之前已經有兩個元素了, 所以這次就一下找到兩對
好數對, 然後再將map中的元素k的value+1,以此類推。
注意:
None
複雜度:
Time Coplexity: O(N)
Space Complexity: O(N)
Code示例:
class Solution {
public int numIdenticalPairs(int[] nums) {
int ans = 0;
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
Integer freq = map.get(num);
if (freq == null) {
map.put(num, 1);
} else {
ans += freq;
map.put(num, freq+1);
}
}
return ans;
}
}
相關文章
- CF1762F Good PairsGoAI
- Number of k-good subarraysGo
- Codeforces Round #213 (Div. 2) A. Good NumberGo
- GOODGo
- Palindrome PairsAI
- Swap Nodes in PairsAI
- A good PlayerGo
- good booksGo
- 024,Swap Nodes in PairsAI
- 24. Swap Nodes in PairsAI
- Leetcode Swap Nodes in PairsLeetCodeAI
- FolderCompareFrame with good layoutGo
- Leetcode 24 Swap Nodes in PairsLeetCodeAI
- 【Lintcode】572. Music PairsAI
- LeetCode-Palindrome PairsLeetCodeAI
- 532. K-diff Pairs in an ArrayAI
- LeetCode 24 Swap Nodes in PairsLeetCodeAI
- Leetcode-Swap Nodes in PairsLeetCodeAI
- Swap Nodes in Pairs leetcode javaAILeetCodeJava
- Some good websites for C++GoWebC++
- Good Bye 2013Go
- How Good Are Your Opinion 2Go
- Cheap ghd straighteners a goodAIGo
- How To Kill Good IdeasGoIdea
- Good documentation or books related to OracleGoOracle
- Good Links related OracleGoOracle
- Good story for dear friends.Go
- 2010//11/24 11.24 好友共享美食 Good Food, Good FriendsGo
- Vim auto-pairs設定選項AI
- 【LeetCode】Palindrome Pairs(336)LeetCodeAI
- CF Div. 3 C Beautiful Triple PairsAI
- Good site on Oracle tech blogGoOracle
- 對maven的通俗理解,goodMavenGo
- Your Prediction Gets As Good As Your DataGo
- Ghd cheap good earthenware oneGo
- Good Coding Skills Are Not Enough (轉)Go
- learn english, a good website to learn englishGoWeb
- good wife真的很好看Go