zoukankan      html  css  js  c++  java
  • search insert position

    题目:

    有两种思路,一种是采用简单的搜索,可以一个一个的向上检索,直到匹配;另外一种是采用折半查找,如果存在array[middle]==target那么直接返回target的位置,否则的话,找到low和high相等的位置,判断数组中此位置的值是否大于等于target,是的话就直接返回low,否则返回low+1;

    第一种思路的代码:

    def true_index_search(array, target):
        index = 0
        while index < len(array):
            if target == array[index]:
                break
            elif target < array[index]:
                break
            else:
                index += 1
        return index

    我测试了第一种方法在leetcode上的效率:

    第二种思路的代码:

    def search_index(array, target):
        high = len(array)
        low = 0
        if high == 0 or array[0] > target:
            return 0
        elif array[high-1] < target:
            return high
        else:
            high -= 1
            while high > low:
                middle = int(low + (high - low)/2)
                if array[middle] == target:
                    return middle
                else:
                    if array[middle] > target:
                        high = middle - 1
                    else:
                        low = middle + 1
            if array[low] >= target:
                return low
            else:
                return low+1

    我测试了第二种方法在leetcode上的效率:

    我写了一个测试程序,判断第二个程序的正确率:

    import random
    def test_function():
        times = 100000
        right = 0
        for time in range(times):
            len = random.randint(0, 1000)
            array = []
            for i in range(len):
                array.append(random.randint(0, 1000))
            array_set = list(set(array))
            array_set.sort()
            target = random.randint(0, 10000)
            myvalue = search_index(array_set, target)
            true_value = true_index_search(array_set, target)
            if myvalue == true_value:
                right += 1
        return float(right)/float(times)
    
    if __name__ == "__main__":
        value = test_function()
        print(value)

    结果如下:

     可以看到第二种方法和第一种方法的效果相同,但是第二种方法的效率要比第一种方法高得多。在用折半查找做这道题的时候, 要特别注意判断条件。

  • 相关阅读:
    红帽7 Shell编程
    红帽7 vim编辑器
    红帽7 管道符、重定向与环境变量
    红帽7 systemctl管理服务的启动、重启、停止、重载、查看状态等常用命令
    python 装饰器详解
    红帽7 常用系统命令
    转 JSON详解
    转 C# using 三种使用方式
    存储过程详解 转
    使用Mybatis-Generator自动生成Dao、Model、Mapping相关文件(转)
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/9202552.html
Copyright © 2011-2022 走看看