Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- UI
- SOLID
- js
- Linux
- API
- CSS
- nodejs
- PRISMA
- ps
- sqlite
- figma
- PyTorch
- react
- review
- html
- ML
- DB
- frontend
- python
- ts
- Express
- Git
- mongo
- GAN
- postgresql
- C++
- Three
- DM
- vscode
- CV
Archives
- Today
- Total
아카이브
[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 |
Comments