Python 查找排序列表中第一个非负数的函数?

Python function to find the first non-negative number in a sorted list?

我有一个像 nums = [-4,-1,0,3,10] 这样的排序列表,我想找到第一个非负整数的索引。

向我提供了线性时间解决方案:

def find(nums):
  n = len(nums)
  i = 0
  while i < n and nums[i] < 0:
    i += 1
  return i

这个问题有对数解吗?

保证列表中一定有非负整数

Python 标准库有一个非常酷的库,叫做 bisect,它将对列表进行快速二进制搜索。在您的示例中,您可以通过使用 bisect.bisect_right 找到零的“正确”插入点来获取第一个非负数的索引:

from bisect import bisect_right

nums = [-4,-1,0,0,1,3,10]

index = bisect_right(nums, 0)
# 4 -- the index

nums[index]
# 1 -- the number at that index

如果没有非负数,它将 return 一个等于列表长度的索引,因此如果有可能,您将需要对其进行测试。

def find(nums):    
   leave = 0 
   index = -1   
   for num in nums:
       if leave = 0
          index += 1
          if num > -1:
             leave = 1
   print(index)
   return(index)

试试这个。索引从 -1 开始,因为如果第一个元素为正,它仍然会递增一次。离开只是表示停止搜索。