[LeetCode]题解(python):035-Search Insert Position

题目来源:

  https://leetcode.com/problems/search-insert-position/


 

题意分析:

  给定一个排好序的数组和一个target,如果target在数组里面,那么返回他的位置,否者返回他应该插入哪个位置。


 

题目思路:

  这也是一个标准的二分查找。如果没有找到,那么和first和last位置的数比较一下就可以得到答案。


 

代码(python):

  

 1 class Solution(object):
 2     def searchInsert(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: int
 7         """
 8         first = 0;last = len(nums) - 1
 9         while first < last:
10             mid = (first + last + 1) // 2
11             if nums[mid] == target:
12                 return mid
13             if nums[mid] < target:
14                 first = mid + 1
15             else:
16                 last = mid - 1
17         if nums[last] < target:
18             return last + 1
19         if target <= nums[last]:
20             return last
21         if target < nums[first]:
22             return first
23         return first + 1
View Code

 


 

转载请注明出处:http://www.cnblogs.com/chruny/p/4918447.html

转载于:https://www.cnblogs.com/chruny/p/4918447.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值