sorted search increase performance

前端 未结 4 428
野性不改
野性不改 2021-01-29 14:53

Running through exercises on testdome...currently looking at https://www.testdome.com/for-developers/solve-question/9877

Implement function CountNum

4条回答
  •  梦毁少年i
    2021-01-29 15:43

    If you like to implement your own BST, you can try the following code. It is written in Python. You can rewrite it in other languages if required. It passes all the 4 tests.

    def count_numbers(sorted_list, less_than):
    
        if len(sorted_list) == 0 or sorted_list[0] >= less_than:
            return 0
        if sorted_list[-1] < less_than:
            return len(sorted_list)
    
        arr = sorted_list
        def lt_array(low, high, arr):
            mid = low + (high-low+1) //2 
            if arr[mid] >= less_than and arr[mid-1] < less_than:
                return mid
            if arr[mid] > less_than:
                return lt_array(low,mid,arr)
            else:
                return lt_array(mid, high, arr)
        
        return lt_array(0,len(sorted_list)-1, arr)
    

提交回复
热议问题