아카이브

[PS] 가장 가까운 두 수 본문

CS/PS

[PS] 가장 가까운 두 수

Rayi 2025. 3. 21. 11:11

문제

Given an array of distinct integers, determine the mininum absolute difference between any two elements, Print all element pairs with that difference in ascending order.

예시

Input : count = 4, numbers = [6,2,4,10]

Output : [[2, 4], [4, 6]]

Explanation : The minimum absolute difference is 2 and the pairs with that difference are (2, 4) and (4, 6). When printing element pairs (i,j), they should be ordered ascending first by i and then by j.

조건

  • 2 <= n <= 10^5
  • -10^9 <= numbers[i] <= 10^9

배열을 정렬한 뒤, 각 인접한 두 요소의 차들을 비교하여 가장 작은 차를 구합니다.

 

이후, 해당 차를 가지는 두 인접한 요소들을 차례대로 출력합니다.

function closestNumbers(count, numbers) {
    numbers.sort((a, b) => a - b);

    let minDiff = Infinity;

    for (let i=0; i<count-1; i++) {
        const diff = numbers[i + 1] - numbers[i];
        if (diff < minDiff) {
            minDiff = diff;
        }
    }

    for (let i=0; i<count-1; i++) {
        const diff = numbers[i + 1] - numbers[i];
        if (diff === minDiff) {
            console.log(numbers[i], numbers[i + 1]);
        }
    }
}

시간 복잡도 : O(n)

공간 복잡도 : O(1)

728x90
Comments