โจทย์
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.
เงื่อนไข
0 ≤ length ≤ 100,000
ตัวอย่าง
อินพุต:
numbers = [4, 0, -2, -7]
ผลลัพธ์ที่คาดหวัง:
expected = 2
อินพุต:
std::vector<long long> numbers = {4, 0, -2, -7};
ผลลัพธ์ที่คาดหวัง:
long long expected = 2;
อินพุต:
long[] numbers = new long[] {4, 0, -2, -7};
ผลลัพธ์ที่คาดหวัง:
long expected = 2;
คำอธิบาย
-2 at index 2 is the first negative value.
อินพุต:
numbers = [1, 2, 3]
ผลลัพธ์ที่คาดหวัง:
expected = -1
อินพุต:
std::vector<long long> numbers = {1, 2, 3};
ผลลัพธ์ที่คาดหวัง:
long long expected = -1;
อินพุต:
long[] numbers = new long[] {1, 2, 3};
ผลลัพธ์ที่คาดหวัง:
long expected = -1;
คำอธิบาย
There are no negative numbers, so the answer is -1.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
ต้องหาตำแหน่งแรกที่ค่าต่ำกว่า 0 เท่านั้น
คำใบ้ 2
ไล่จากซ้ายไปขวาแล้วหยุดทันทีเมื่อเจอ
คำใบ้ 3
ถ้าไม่มีค่าติดลบ ให้คืนค่ากรณีไม่พบตามที่กำหนด
ความซับซ้อนที่คาดหวัง
เวลา O(n), หน่วยความจำเพิ่ม O(1)
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน