iT邦幫忙

0

Day 6: 35. Search Insert Position

  • 分享至 

  • xImage
  •  

Given a sorted array of distinct integers 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 must write an algorithm with O(log n) runtime complexity.

Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:
Input: nums = [1,3,5,6], target = 7
Output: 4
解題思路
1.找出目標值應插入的位置。
2.使用二分搜尋法。
3.若沒找到,left會停在應插入的位置。
https://ithelp.ithome.com.tw/upload/images/20251012/20179424tq3HiJ9psE.png


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言