博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python - Search Insert Position
阅读量:4030 次
发布时间:2019-05-24

本文共 1022 字,大约阅读时间需要 3 分钟。

标签: 
 
1027人阅读 
(0) 
 
 
分类:
博客域名:
原题页面:
题目类型:二分查找
难度评价:★★
本文地址:

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Here are few examples.

[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

二分查找的一个变种。如果找到了target,就返回下标(正常的二分查找逻辑),否则就返回插入的位置。二分查找容易搞晕的是到底是返回left还是right,注意到left最终一定停在target上,或停在target的“位置”的右边,所以显然找不到target时,应该返回left的下标作为插入位置。

[python] 
  1. class Solution:  
  2.     # @param A, a list of integers  
  3.     # @param target, an integer to be inserted  
  4.     # @return integer  
  5.     def searchInsert(self, A, target):  
  6.         if None == A:  
  7.             return 0  
  8.         len_A = len(A)  
  9.         if target > A[len_A - 1]:  
  10.             return len_A  
  11.         if target < A[0]:  
  12.             return 0  
  13.   
  14.         left = 0  
  15.         right = len_A - 1  
  16.         while left <= right:    # also can be left < right  
  17.             mid = (left + right) / 2  
  18.             if A[mid] < target:  
  19.                 left = mid + 1  
  20.             elif A[mid] > target:  
  21.                 right = mid - 1  
  22.             else:  
  23.                 return mid  
  24.         return left  
你可能感兴趣的文章
CCF 分蛋糕
查看>>
解决python2.7中UnicodeEncodeError
查看>>
小谈python 输出
查看>>
Django objects.all()、objects.get()与objects.filter()之间的区别介绍
查看>>
python:如何将excel文件转化成CSV格式
查看>>
Django 的Error: [Errno 10013]错误
查看>>
机器学习实战之决策树(一)
查看>>
[LeetCode By Python] 2 Add Two Number
查看>>
python 中的 if __name__=='__main__' 作用
查看>>
机器学习实战之决策树二
查看>>
[LeetCode By Python]7 Reverse Integer
查看>>
[LeetCode By Python]9. Palindrome Number
查看>>
[leetCode By Python] 14. Longest Common Prefix
查看>>
[LeetCode By Python]107. Binary Tree Level Order Traversal II
查看>>
[LeetCode By Python]108. Convert Sorted Array to Binary Search Tree
查看>>
[leetCode By Python]111. Minimum Depth of Binary Tree
查看>>
[LeetCode By Python]118. Pascal's Triangle
查看>>
[LeetCode By Python]121. Best Time to Buy and Sell Stock
查看>>
[LeetCode By Python]122. Best Time to Buy and Sell Stock II
查看>>
[LeetCode By Python]125. Valid Palindrome
查看>>