Tất cả thử thách
Trung bình 0 người đã giải Tỷ lệ chấp nhận 0%

Nearest Smaller Value to the Left

For each number, find the closest earlier position containing a strictly smaller number.

Bạn sẽ học được gì

  • Keep a stack of useful candidates
  • Pop values that can never be the answer
  • Solve the problem in linear time

Đề bài

Xem bản dịch

For each number, find the closest earlier position containing a strictly smaller number. Equal numbers do not qualify. Positions start at 1; use 0 when there is no smaller number to the left.

Implement nearest_smaller_value(numbers).

Input

numbers: Numbers in their original order.

Output

Return one earlier position (or 0) for every input value.

Ràng buộc

0…200,000 integers, each between −1,000,000,000 and 1,000,000,000. Empty input returns an empty list.

Ví dụ

Ví dụ 1
Đầu vào:
numbers = [4, 2, 5, 3]

Kết quả mong đợi:
expected = [0, 0, 2, 2]
Đầu vào:
std::vector<long long> numbers = {4, 2, 5, 3};

Kết quả mong đợi:
std::vector<long long> expected = {0, 0, 2, 2};
Đầu vào:
long[] numbers = new long[] {4, 2, 5, 3};

Kết quả mong đợi:
long[] expected = new long[] {0, 0, 2, 2};

Giải thích

4 has no earlier value and 2 has no smaller earlier value. Both 5 and 3 find the value 2 at position 2.

Ví dụ 2
Đầu vào:
numbers = [2, 2, 2]

Kết quả mong đợi:
expected = [0, 0, 0]
Đầu vào:
std::vector<long long> numbers = {2, 2, 2};

Kết quả mong đợi:
std::vector<long long> expected = {0, 0, 0};
Đầu vào:
long[] numbers = new long[] {2, 2, 2};

Kết quả mong đợi:
long[] expected = new long[] {0, 0, 0};

Giải thích

Earlier equal values are not strictly smaller. Every answer is 0.

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

For each position, you need the closest earlier value that is strictly smaller, not smaller-or-equal.

Gợi ý 2

Maintain a monotonic stack of candidate values with their positions while scanning left to right.

Gợi ý 3

Pop equal or larger values, since they can never be the nearest smaller answer for later elements.

Độ phức tạp mong đợi

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

Chưa có lời giải nào đạt. Giải bài này để giành hạng nhất.

Học hỏi từ người khác

Lời giải cộng đồng

Chưa có lời giải nào được chia sẻ. Hãy giải thử thách này để đăng lời giải đầu tiên.