본문으로 바로가기

[HakcerLank] Pairs - 문제풀이

category 알고리즘/HackerRank 2022. 3. 25. 04:39

Description

주어진 배열의 두 요소의 차이값이 k과 일치하는 개수를 찾아 반환하는 문제입니다.

Solution 1. Set

public static int pairs(int k, List<Integer> arr) {
    // Write your code here
    Collections.sort(arr);
    Set<Integer> set = new HashSet<>();

    int cnt = 0;
    for (int i = 0; i < arr.size(); i++) {
        set.add(arr.get(i));
        if(set.contains(arr.get(i)-k)){
            cnt++;
        }
    }
    return cnt;
}

오름차순으로 리스트를 정렬 한 뒤 set에 요소를 넣고 현재 요소-k값이 있는지 검증하여 cnt를 올려줍니다. 중복되는 값이 들어가지 않기 때문에 중복 카운팅 없이 set를 이용해서 끝 요소까지 검증해주면 됩니다.

Reference

 

 

Pairs | HackerRank

Given N numbers, count the total pairs of numbers that have a difference of K.

www.hackerrank.com