Leetcode-34-Search Insert Position-(Medium)

二分法查找需要插入的位置,需要注意两点

1、如果元素不存在,停止的时候start Index刚好是需要插入的位置

2、如果元素存在,需要向前追溯找到非目标元素的起始边界

 

#!/usr/local/bin/python3
# -*- coding: utf-8 -*-
__author__ = 'qqvipfunction'

class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """

        return self.binary_search(nums, 0, len(nums) - 1, target)



        #二分查找算法
    def binary_search(self, nums, start, end, targrt):
        if start > end:
            print(start, end)
            return start if start > 0 else 0
        mid = start + (end - start)//2
        if nums[mid] > targrt:
            return self.binary_search(nums, start, mid - 1, targrt)
        elif nums[mid] < targrt:
            return self.binary_search(nums, mid + 1, end, targrt)
        else:
            index = mid
            for i in range(mid - 1, -1, -1):
                if nums[i] == targrt:
                    index = i;
                else:
                    break
            return index



if __name__ == '__main__':
    s = Solution()
    print(s.searchInsert([1], 0))

  

posted @ 2017-01-16 16:21  兜兜有糖的博客  阅读(277)  评论(0编辑  收藏  举报