티스토리 뷰

leetcode.com/problems/number-of-good-pairs/

 

Number of Good Pairs - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

Given an array of integers nums.

A pair (i,j) is called good if nums[i] == nums[j] and i < j.

Return the number of good pairs.

배열을 주면 배열의 인덱스 별 조건에 맞는 쌍을 찾아서 출력시키는 것이다.

조건은 두 값이 같고 첫번째 인덱스보다 두번째 인덱스가 커야댐..

간단하게 2중for문(O(n²)) 돌리면 풀린다.

class Solution {
public:
    int numIdenticalPairs(vector<int>& nums) {
        int cnt = 0;
        for (int i = 0; i < nums.size();  i++) {
            for (int j = i; j < nums.size(); j++) {
                if ((nums[i] == nums[j]) && i < j) {
                    cnt++;
                }
            }
        }
        return cnt;
    }
};
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함