Post

[Programmers] #120890 - 가까운 수 [Java][C++][Python]

[Programmers] #120890 - 가까운 수 [Java][C++][Python]

문제 링크


1. 아이디어

배열에서 $n$과 가장 가까운 수를 구하되, 거리가 같으면 더 작은 수를 고르는 문제다. 거리가 가까운 쪽이 우선이고 거리가 같으면 값이 작은 쪽이 우선이므로, (거리, 값) 순으로 비교한 최솟값이 답이다.


2. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
    public int solution(int[] array, int n) {
        int ans = 0;
        int diff = 100;

        for (int x : array) {
            if (Math.abs(x - n) < diff) {
                ans = x;
                diff = Math.abs(x - n);
            } else if (Math.abs(x - n) == diff && x < ans) {
                ans = x;
            }
        }

        return ans;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <bits/stdc++.h>
using namespace std;

int solution(vector<int> array, int n) {
    int ans = 0;
    int diff = 100;

    for (int x : array) {
        if (abs(x - n) < diff) {
            ans = x;
            diff = abs(x - n);
        } else if (abs(x - n) == diff && x < ans) {
            ans = x;
        }
    }

    return ans;
}
1
2
def solution(array, n):
    return min(array, key=lambda x: (abs(x - n), x))

key에 (차이, 값) 튜플을 줘서 차이가 같으면 값이 작은 쪽이 뽑히게 했다.


This post is licensed under CC BY 4.0 by the author.