-
[LeetCode] 1512. Number of Good Pairs c++Coding Test/LeetCode 2022. 10. 10. 17:00728x90
- 문제
Given an array of integers nums, return the number of good pairs.
A pair (i, j) is called good if nums[i] == nums[j] and i < j.
Input: nums = [1,2,3,1,1,3] Output: 4 Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
- 문제 해결
class Solution { public: int numIdenticalPairs(vector<int>& nums) { int answer(0), len = nums.size(); for(int i = 0; i < len - 1; i++){ for(int j = i + 1; j < len; j++){ if(nums[i] == nums[j]) answer++; } } return answer; } };
다른 풀이
int numIdenticalPairs(vector<int>& nums) { int ans=0; unordered_map<int,int>mp; for(int &it:nums){ ans += mp[it]++; } return ans; }
다른 풀이2
class Solution { public: int numIdenticalPairs(vector<int>& nums) { int mem[101] ={0}; int sum=0; for(int i=0; i < nums.size(); i++){ sum += mem[nums[i]]; ++mem[nums[i]]; } return sum; } };
728x90'Coding Test > LeetCode' 카테고리의 다른 글
[LeetCode] 590. N-ary Tree Postorder Traversal c++ (0) 2022.11.29 [LeetCode] 1971. Find if Path Exists in Graph c++ (0) 2022.11.29 [LeetCode] 1672. Richest Customer Wealth c++ (0) 2022.10.10 [LeetCode] 1470. Shuffle the Array c+ (0) 2022.10.10 [LeetCode] 2011. Final Value of Variable After Performing Operations c++ (0) 2022.10.10