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
- 024,Swap Nodes in PairsAI
- Leetcode 24 Swap Nodes in PairsLeetCodeAI
- [LeetCode] 336. Palindrome PairsLeetCodeAI
- 【Lintcode】572. Music PairsAI
- Good site on Oracle tech blogGoOracle
- Some good websites for C++GoWebC++
- [ARC159F] Good DivisionGo
- CF1925D Good TripGo
- Codeforces 264B. Good SequencesGo
- rember me all time good luckREMGo
- ABC 328F Good Set QueryGo
- Vim auto-pairs設定選項AI
- CF Div. 3 C Beautiful Triple PairsAI
- [LeetCode] 1497. Check If Array Pairs Are Divisible by kLeetCodeAI
- 題解 CF997E 【Good Subsegments】Go
- This is a good question,初學者都犯暈!Go
- JavaScript Number()JavaScript
- E - Remove Pairs(狀壓dp+博弈論)REMAI
- Diff-prime Pairs(思維+素數篩)AI
- Solution - Atcoder ABC263G Erasing Prime PairsAI
- [LeetCode] 3184. Count Pairs That Form a Complete Day ILeetCodeAIORM
- 얘랑 있을 때 좋다 Good to be with YouGo
- 力扣 1512. 好數對的數目(超簡單暴力解法)力扣
- 【LeetCode】493. Reverse Pairs 翻轉對(Hard)(JAVA)LeetCodeAIJava
- Kata:Hamming number
- JavaScript Number toLocaleString()JavaScript
- JavaScript Number toString()JavaScript
- Number.NaNNaN
- JavaScript Number 物件JavaScript物件
- Leetcode Number of islandsLeetCode
- 兩種解法搞定Swap Nodes in Pairs演算法題AI演算法
- Perfect Number 完美數
- [LeetCode] Third Maximum NumberLeetCode
- [LeetCode] Find the Duplicate NumberLeetCode
- Leetcode 9 Palindrome NumberLeetCode
- Number.parseInt() 方法