[LeetCode]题解(python):035-Search Insert Position
题目来源
https://leetcode.com/problems/search-insert-position/
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.
题意分析
Input: a sorted list of int
Output: the index if the target is found. If not, return the index where it would be if it were inserted in order.
Conditions:找到target所在的位置或者应该插入的位置
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
题目思路
使用二分法找元素,如果找到直接返回index,如果不能找到,此时又first和last两个值,注意到target总是不小于nums[first],所以比较target和first即可,
- 如果target大于nums[first],返回first + 1
- 反之返回first
注意到在二分法当中first可能会加1溢出数组,所以在上面步骤当中要在比较前加入判断first是否溢出数组
AC代码(Python)
1 _author_ = "YE" 2 # -*- coding:utf-8 -*- 3 4 class Solution(object): 5 def searchInsert(self, nums, target): 6 """ 7 :type nums: List[int] 8 :type target: int 9 :rtype: int 10 """ 11 len1 = len(nums) 12 first = 0 13 last = len1 14 while first < last: 15 mid = (first + last) // 2 16 if nums[mid] == target: 17 return mid 18 elif nums[mid] < target: 19 first = mid + 1 20 else: 21 last = mid - 1 22 # print(first,last) 23 if first < len1 and nums[first] < target: 24 return first + 1 25 return first 26 27 s = Solution() 28 nums = [1,3] 29 target = 2 30 print(s.searchInsert(nums, target))