Đề bài
Find the position (counting from 0) of the first negative number in the list.
Implement first_negative_index(numbers).
Input
numbers: The list of integers.
Output
Return the index, or -1 if there are no negative numbers.
Ràng buộc
0 ≤ length ≤ 100,000
Ví dụ
Đầu vào:
numbers = [4, 0, -2, -7]
Kết quả mong đợi:
expected = 2
Đầu vào:
std::vector<long long> numbers = {4, 0, -2, -7};
Kết quả mong đợi:
long long expected = 2;
Đầu vào:
long[] numbers = new long[] {4, 0, -2, -7};
Kết quả mong đợi:
long expected = 2;
Giải thích
-2 at index 2 is the first negative value.
Đầu vào:
numbers = [1, 2, 3]
Kết quả mong đợi:
expected = -1
Đầu vào:
std::vector<long long> numbers = {1, 2, 3};
Kết quả mong đợi:
long long expected = -1;
Đầu vào:
long[] numbers = new long[] {1, 2, 3};
Kết quả mong đợi:
long expected = -1;
Giải thích
There are no negative numbers, so the answer is -1.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
You only need the first position where a value is below zero.
Gợi ý 2
Scan from left to right and stop as soon as you find one.
Gợi ý 3
If no negative value appears, be sure to return the missing-case value.
Độ phức tạp mong đợi
O(n) time, O(1) 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.