Skip to content

Commit 44ad0cc

Browse files
committed
leetcode.com 34. Find First and Last Position of Element in Sorted Array
문제 링크: https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array
1 parent f242ef7 commit 44ad0cc

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def searchRange(self, nums: List[int], target: int) -> List[int]:
6+
if len(nums) == 0:
7+
return [-1, -1]
8+
9+
idx = self.binary_search(nums, target)
10+
11+
if idx == -1:
12+
return [-1, -1]
13+
14+
return self.two_pointer(nums, target, idx)
15+
16+
def binary_search(self, nums: List[int], target: int) -> int:
17+
left, right = 0, len(nums) - 1
18+
19+
while left <= right:
20+
mid = (left + right) // 2
21+
22+
if target == nums[mid]:
23+
return mid
24+
25+
if target < nums[mid]:
26+
right = mid - 1
27+
else: # nums[mid] < target
28+
left = mid + 1
29+
30+
return -1
31+
32+
def two_pointer(self, nums: List[int], target, bgn: int) -> List[int]:
33+
left, right = bgn, bgn
34+
35+
while 0 <= left and nums[left] == target:
36+
left -= 1
37+
38+
left += 1
39+
40+
while right <= len(nums) - 1 and nums[right] == target:
41+
right += 1
42+
43+
right -= 1
44+
45+
return [left, right]
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from unittest import TestCase
2+
from main import Solution
3+
4+
5+
class TestSolution(TestCase):
6+
def test1_search_range(self):
7+
sln = Solution()
8+
self.assertEqual([3, 4], sln.searchRange([5, 7, 7, 8, 8, 10], 8))
9+
10+
def test2_search_range(self):
11+
sln = Solution()
12+
self.assertEqual([-1, -1], sln.searchRange(nums=[5, 7, 7, 8, 8, 10], target=6))
13+
14+
def test3_search_range(self):
15+
sln = Solution()
16+
self.assertEqual([-1, -1], sln.searchRange(nums=[], target=0))
17+
18+
def test4_search_range(self):
19+
sln = Solution()
20+
self.assertEqual([0, 0], sln.searchRange(nums=[1], target=1))
21+
22+
def test81_search_range(self):
23+
sln = Solution()
24+
self.assertEqual([1, 1], sln.searchRange(nums=[1, 4], target=4))

0 commit comments

Comments
 (0)