#35

Search Insert Position

pupil · 435 · lc easy +25 · verified · 50.8% accepted · 18,679 likes · top 39%

play →

Description

Given a sorted array of distinct integers and a target, return the index where target is found, or the index at which it would be inserted to keep the array sorted. Run in O(log n) time.

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

Code

1
2
3