[leetcode] 35. Search Insert Position

섬섬's 개발일지·2022년 1월 23일
0

leetcode

목록 보기
3/23

leetcode.35

35. Search Insert Position (Easy)

문제

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

Costraints :

  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums contains distinct values sorted in ascending order.
  • -10^4 <= target <= 10^4

풀이

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        left = 0
        right = len(nums) - 1
        
        while left < right :
            mid = (left+right) // 2
            if nums[mid] < target :
                left = mid + 1
            else :
                right = mid - 1
        
        if nums[left] >= target : return left
        else : return left + 1
profile
섬나라 개발자

0개의 댓글