[PS] 가장 가까운 두 수

2025. 3. 21. 11:11·CS/PS

문제

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

'CS > PS' 카테고리의 다른 글

[PS] 같은 수의 뉴런  (0) 2025.03.21
[PS] Leet | 15. 세 개의 합  (0) 2025.03.21
[PS] Leet | 33. 정렬된 회전 배열에서의 탐색  (0) 2025.03.20
[PS] Leet | 153. 정렬된 회전배열에서의 최소값  (0) 2025.03.20
[PS] Leet | 152. 최댓값을 가지는 하위 배열 - 곱셈  (0) 2025.03.20
'CS/PS' 카테고리의 다른 글
  • [PS] 같은 수의 뉴런
  • [PS] Leet | 15. 세 개의 합
  • [PS] Leet | 33. 정렬된 회전 배열에서의 탐색
  • [PS] Leet | 153. 정렬된 회전배열에서의 최소값
Rayi
Rayi
  • Rayi
    아카이브
    Rayi
  • 전체
    오늘
    어제
    • 분류 전체보기 (262)
      • CS (40)
        • ML (3)
        • CV (2)
        • PS (34)
      • Reveiw (17)
        • Paper (17)
        • Github (0)
      • Pytorch (5)
      • Language (58)
        • Python (7)
        • JavaScript (32)
        • TypeScript (16)
        • C++ (3)
      • IDE (12)
      • Git (13)
      • Frontend (71)
        • React (8)
        • SolidJS (20)
        • CSS (12)
      • UI (3)
      • Backend (15)
        • DB (17)
        • Node.js (11)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Three
    GAN
    CV
    js
    C++
    postgresql
    Express
    ML
    UI
    PRISMA
    API
    CS
    figma
    DB
    mongo
    deploy
    review
    html
    PyTorch
    CSS
    ps
    react
    backend
    python
    vscode
    Git
    SOLID
    frontend
    ts
    nodejs
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
Rayi
[PS] 가장 가까운 두 수
상단으로

티스토리툴바