모든 챌린지
보통 1명 해결 정답률 100.0%

K-Nearest Neighbors Classifier

Predict a label by majority vote of the k closest training points.

배우게 될 내용

  • Find the closest training points
  • Predict by majority vote
  • Break ties deterministically

문제

번역본 보기

K-nearest neighbors (KNN) classifies a new point by looking at the k training points closest to it and taking the most common label.

  1. Compute the Euclidean distance from query to every point.
  2. Sort the points by distance; if two distances are equal, the point with the smaller index comes first.
  3. Take the first k points and count their labels.
  4. Return the label with the most votes. If labels tie, return the tied label whose closest point comes first in the sorted order.

Implement knn_predict(points, labels, query, k).

Input

points: The training points, each a list of coordinates.

labels: The label of each point.

query: The point to classify.

k: How many neighbors vote.

Output

Return the predicted label.

제약 조건

1 ≤ k ≤ number of points ≤ 1,000

1 ≤ dimensions ≤ 20

-1,000 ≤ each coordinate ≤ 1,000

예시

예시 1
입력:
points = [
    [1.0, 1.0],
    [2.0, 2.0],
    [8.0, 8.0],
    [9.0, 9.0]
]
labels = ["A", "A", "B", "B"]
query = [3.0, 3.0]
k = 3

예상 출력:
expected = "A"
입력:
std::vector<std::vector<double>> points = {
    {1.0, 1.0},
    {2.0, 2.0},
    {8.0, 8.0},
    {9.0, 9.0}
};
std::vector<std::string> labels = {"A", "A", "B", "B"};
std::vector<double> query = {3.0, 3.0};
long long k = 3;

예상 출력:
std::string expected = "A";
입력:
double[][] points = new double[][] {
    new double[] {1.0, 1.0},
    new double[] {2.0, 2.0},
    new double[] {8.0, 8.0},
    new double[] {9.0, 9.0}
};
string[] labels = new string[] {"A", "A", "B", "B"};
double[] query = new double[] {3.0, 3.0};
long k = 3;

예상 출력:
string expected = "A";

설명

Distances from (3, 3): (2, 2) ≈ 1.41, (1, 1) ≈ 2.83, (8, 8) ≈ 7.07. The 3 nearest labels are A, A and B, so the answer is A.

예시 2
입력:
points = [
    [0.0, 0.0],
    [4.0, 0.0],
    [0.0, 4.0],
    [4.0, 4.0]
]
labels = ["red", "blue", "blue", "red"]
query = [1.0, 1.0]
k = 2

예상 출력:
expected = "red"
입력:
std::vector<std::vector<double>> points = {
    {0.0, 0.0},
    {4.0, 0.0},
    {0.0, 4.0},
    {4.0, 4.0}
};
std::vector<std::string> labels = {"red", "blue", "blue", "red"};
std::vector<double> query = {1.0, 1.0};
long long k = 2;

예상 출력:
std::string expected = "red";
입력:
double[][] points = new double[][] {
    new double[] {0.0, 0.0},
    new double[] {4.0, 0.0},
    new double[] {0.0, 4.0},
    new double[] {4.0, 4.0}
};
string[] labels = new string[] {"red", "blue", "blue", "red"};
double[] query = new double[] {1.0, 1.0};
long k = 2;

예상 출력:
string expected = "red";

설명

The nearest point is (0, 0) (red); the next two, (4, 0) and (0, 4), are at the same distance, so the smaller index (4, 0) (blue) wins the tie. Red and blue have one vote each, and red's point came first, so the answer is red.

접근 방법

먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.

힌트 1

Measure each point’s Euclidean distance to the query, then rank points by distance with smaller indices breaking ties.

힌트 2

Only the first k sorted points vote, so the final label depends on a tiny subset of the training set.

힌트 3

If vote counts tie, use the label whose nearest contributing point appears earliest in the sorted neighbor list.

예상 복잡도

O(n log n) time, O(n) extra space

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

코더마다 가장 좋은 통과 풀이입니다. 더 빠르고, 메모리를 덜 쓰고, 평가가 좋은 풀이가 위에 옵니다.

# 코더 언어 시간 메모리 AI 평가 풀이
1 ННикита Python 930 ms - 5/5 코드 보기

다른 사람의 풀이 보기

커뮤니티 솔루션

스포일러: 아래에 1개 전체 솔루션 있음 먼저 직접 풀어보세요. 다른 개발자의 코드와 AI 리뷰도 참고할 수 있습니다. 로그인하고 문제를 풀면 토론에 참여할 수 있습니다.