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.
Example 1:
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.
Example 2:
Input: nums = [1,1,1,1]
Output: 6
Explanation: Each pair in the array are good.
Example 3:
Input: nums = [1,2,3]
Output: 0
Constraints:
- 1 <= nums.length <= 100
- 1 <= nums[i] <= 100
나의 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
/**
* @param {number[]} nums
* @return {number}
*/
var numIdenticalPairs = function(nums) {
let count =0
for(let i=0; i<nums.length; i++){
for(let j= i+1; j<nums.length; j++){
console.log(nums[i], nums[j])
if(nums[i] === nums[j]) count++
}
}
return count
};
|
cs |
문제를 풀며 느낀 점
- 먼저 pair가 먼지 이해를 못 했었는데 한쌍의 숫자가 똑같은 수면 pair라고 하는 것 같습니다.
이중 for문을 돌면서 i=0부터 순회하고 j= i+1로 반복문을 통해서 만약 nums [i] === nums [j]가 같다면 count++을 하였고 반복문이 끝나면 count를 return 하였습니다.
'코딩 테스트 풀이 🛠' 카테고리의 다른 글
[Leet Code - eazy] 1672. Richest Customer Wealth (0) | 2023.01.28 |
---|---|
[Leet Code - eazy] 771. Jewels and Stones (0) | 2023.01.28 |
[Leet Code - eazy] 1470. Shuffle the Array (0) | 2023.01.28 |
[프로그래머스] 같은 숫자는 싫어 (0) | 2023.01.22 |
[프로그래머스] 직사각형 별찍기 (0) | 2023.01.22 |