โจทย์
Count how many numbers in the list are greater than zero. Zero is neither positive nor negative.
Implement count_positives(numbers).
Input
numbers: The list of integers.
Output
Return the count.
เงื่อนไข
0 ≤ length ≤ 100,000; each value fits in a 64-bit integer
ตัวอย่าง
อินพุต:
numbers = [3, -1, 0, 7, 2]
ผลลัพธ์ที่คาดหวัง:
expected = 3
อินพุต:
std::vector<long long> numbers = {3, -1, 0, 7, 2};
ผลลัพธ์ที่คาดหวัง:
long long expected = 3;
อินพุต:
long[] numbers = new long[] {3, -1, 0, 7, 2};
ผลลัพธ์ที่คาดหวัง:
long expected = 3;
คำอธิบาย
3, 7 and 2 are positive: 3.
อินพุต:
numbers = [0, 0, -5]
ผลลัพธ์ที่คาดหวัง:
expected = 0
อินพุต:
std::vector<long long> numbers = {0, 0, -5};
ผลลัพธ์ที่คาดหวัง:
long long expected = 0;
อินพุต:
long[] numbers = new long[] {0, 0, -5};
ผลลัพธ์ที่คาดหวัง:
long expected = 0;
คำอธิบาย
No value is above zero: 0.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
นับเฉพาะตัวเลขที่มากกว่า 0 เท่านั้น
คำใบ้ 2
โจทย์นี้คือการนับแบบกรองจากรายการ
คำใบ้ 3
อย่านับ 0 เพราะมันไม่ใช่ทั้งบวกและลบ
ความซับซ้อนที่คาดหวัง
เวลา O(n), หน่วยความจำเพิ่ม O(1)
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน