Skip to content

Latest commit

 

History

History
34 lines (26 loc) · 1.62 KB

풀이_LC35.md

File metadata and controls

34 lines (26 loc) · 1.62 KB

😼 LeetCode 35. Search Insert Position

  • Date : 2021.07.18(일)
  • Time : 10분

Problem

  • 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.

Constraints

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

Example

  • Input: nums = [1,3,5,6], target = 2
  • Output: 1



풀이

    def searchInsert(self, nums: List[int], target: int) -> int:
        for i in range(0, len(nums),1):
            if nums[i] == target:
                return i
            elif nums[i] > target:
                return i
        return len(nums)

: 이 문제는 target의 위치를 정해주는 문제이다. 먼저 Target의 숫자가 이미 nums array 안에 존재한다면 원래의 위치를 return 해주면 되기 때문에 ===를 이용해서 return을 해주었다. 그리고 만약 그 값이 존재하지 않는다면 두개의 경우가 있다. 첫번째로, 이미 존재하는 배열안에 들어갈 수 있는 경우가 있다. 이것은 target 보다 큰 값이 이미 nums안에 존재하는 것이다. 그렇다면 나보다 큰 값을 만나는 경우 그 인덱스를 뺏어서 내가 쓰면 된다. 두번째는 내가 현재 nums array의 있는 모든 값들보다 큰 경우이다. 이 경우는 for문을 다 돌때까지 return으로 코드가 끝나지 않았을테니 마지막에 맨 마지막 인덱스를 부여해준다.