[LeetCode][Python3] 34. Find First and Last Position of Element in Sorted Array
2018. 11. 11. 00:54 |
프로그래밍/LeetCode
Problem :
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array
My Solution :
class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
def search(low, high, target):
while low < high:
mid = (low + high) // 2
if nums[mid] < target:
low = mid + 1
else:
high = mid
return low
left = search(0, len(nums), target)
if left == len(nums) or nums[left] != target:
return [-1, -1]
right = search(left+1, len(nums), target+1)-1
return [left, right]
Comment :
binary search를 수행하는데, high를 len(nums)-1이 아니라 len(nums)로 잡은게 핵심이다. 그로 인해 right 값을 target+1의 index - 1로 구할 수 있게 된다.
'프로그래밍 > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 49. Group Anagrams (0) | 2018.11.14 |
---|---|
[LeetCode][Python3] 48. Rotate Image (0) | 2018.11.13 |
[LeetCode][Python3] 46. Permutations (0) | 2018.11.12 |
[LeetCode][Python3] 36. Valid Sudoku (0) | 2018.11.11 |
[LeetCode][Python3] 22. Generate Parentheses (0) | 2018.11.10 |
[LeetCode][Python3] 19. Remove Nth Node From End of List (0) | 2018.11.09 |
[LeetCode][Python3] 17. Letter Combinations of a Phone Number (0) | 2018.11.09 |
[LeetCode][Python3] 11. Container With Most Water (0) | 2018.11.07 |
최근에 달린 댓글 최근에 달린 댓글