본문 바로가기
IT/LeetCode

[LeetCode] 35. Search Insert Position

by 강천구 2022. 7. 22.

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

 

Constraints:

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

target이 주어진 수열 중 어디에 들어가는지를 찾는 문제이다.

while을 이용하여 전체 수열을 돌며 해당 인덱스의 수열 값이 target 값보다 큰지 확인하여 결과를 전달한다.

 

class Solution:
   def searchInsert(self, nums, target):
       i = 0
       while nums[i] < target:
           i += 1
           if i >= len(nums):
               break
       return i

 

 

문제 출처 : https://leetcode.com/problems/search-insert-position/

 

Search Insert Position - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Github : https://github.com/kkkkang1009/leetcode/blob/master/leetcode_35.py

 

GitHub - kkkkang1009/leetcode: leetcode

leetcode. Contribute to kkkkang1009/leetcode development by creating an account on GitHub.

github.com

 

반응형

'IT > LeetCode' 카테고리의 다른 글

[LeetCode] 53. Maximum Subarray  (0) 2022.08.15
[LeetCode] 38. Count and Say  (0) 2022.07.22
[LeetCode] 28. Implement strStr()  (0) 2022.07.22
[Leetcode] 27. Remove Element  (0) 2022.07.22
[LeetCode] 26. Remove Duplicates from Sorted Array  (0) 2022.07.22

댓글