ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

One-Hot Encoding

Turn categories into vectors with a single 1, the input format for classifiers and embeddings.

สิ่งที่คุณจะได้เรียนรู้

  • Map categories to vector positions
  • Build one-hot rows for each label
  • Prepare categorical data for models

โจทย์

ดูฉบับแปล

Models need numbers, not words. One-hot encoding turns each category into a vector with one position per category: 1 at the category's position and 0 everywhere else.

Order the categories alphabetically. For each label, output its one-hot vector.

Implement one_hot(labels).

Input

labels: A list of category names.

Output

Return a matrix with one row per label and one column per distinct category (alphabetical order).

เงื่อนไข

1 ≤ length ≤ 1,000

Each label is 1 to 20 characters

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
labels = ["red", "green", "blue", "green"]

ผลลัพธ์ที่คาดหวัง:
expected = [
    [0, 0, 1],
    [0, 1, 0],
    [1, 0, 0],
    [0, 1, 0]
]
อินพุต:
std::vector<std::string> labels = {"red", "green", "blue", "green"};

ผลลัพธ์ที่คาดหวัง:
std::vector<std::vector<long long>> expected = {
    {0, 0, 1},
    {0, 1, 0},
    {1, 0, 0},
    {0, 1, 0}
};
อินพุต:
string[] labels = new string[] {"red", "green", "blue", "green"};

ผลลัพธ์ที่คาดหวัง:
long[][] expected = new long[][] {
    new long[] {0, 0, 1},
    new long[] {0, 1, 0},
    new long[] {1, 0, 0},
    new long[] {0, 1, 0}
};

คำอธิบาย

The categories in alphabetical order are blue, green, red. So red → [0, 0, 1], green → [0, 1, 0] and blue → [1, 0, 0].

ตัวอย่างที่ 2
อินพุต:
labels = ["yes"]

ผลลัพธ์ที่คาดหวัง:
expected = [
    [1]
]
อินพุต:
std::vector<std::string> labels = {"yes"};

ผลลัพธ์ที่คาดหวัง:
std::vector<std::vector<long long>> expected = {
    {1}
};
อินพุต:
string[] labels = new string[] {"yes"};

ผลลัพธ์ที่คาดหวัง:
long[][] expected = new long[][] {
    new long[] {1}
};

คำอธิบาย

There is only one category, so every vector is [1].

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

Find the distinct categories first, then sort them alphabetically to define the column order.

คำใบ้ 2

For each label, place a 1 only in the column matching that label and 0 everywhere else.

คำใบ้ 3

Make sure duplicate labels produce identical rows, since the output has one row per input label.

ความซับซ้อนที่คาดหวัง

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

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก