Add 2 more exercises
This commit is contained in:
parent
89071996f3
commit
2f32bdc7b9
26
leetcode/69_sqrtx.py
Normal file
26
leetcode/69_sqrtx.py
Normal file
@ -0,0 +1,26 @@
|
||||
import pytest
|
||||
|
||||
|
||||
class Solution:
|
||||
def mySqrt(self, x: int) -> int:
|
||||
left, right = 0, x
|
||||
while left <= right:
|
||||
mid = left + (right - left) // 2
|
||||
val = mid * mid
|
||||
if val <= x < (mid + 1) * (mid + 1):
|
||||
return mid
|
||||
elif x < val:
|
||||
right = mid - 1
|
||||
else:
|
||||
left = mid + 1
|
||||
return 0
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def solution():
|
||||
return Solution()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("x, expected", [(4, 2), (8, 2)])
|
||||
def test_my_sqrt(solution: Solution, x: int, expected: int):
|
||||
assert solution.mySqrt(x) == expected
|
41
leetcode/81_search_in_rotated_sorted_array_ii.py
Normal file
41
leetcode/81_search_in_rotated_sorted_array_ii.py
Normal file
@ -0,0 +1,41 @@
|
||||
import pytest
|
||||
|
||||
|
||||
class Solution:
|
||||
def search(self, nums: list[int], target: int) -> bool:
|
||||
low, high = 0, len(nums) - 1
|
||||
while low <= high:
|
||||
breakpoint()
|
||||
mid = low + (high - low) // 2
|
||||
if nums[mid] == target:
|
||||
return True
|
||||
|
||||
if nums[mid] >= nums[low]:
|
||||
if nums[low] <= target <= nums[mid]:
|
||||
high = mid - 1
|
||||
else:
|
||||
low = mid + 1
|
||||
else:
|
||||
if nums[mid] <= target <= nums[high]:
|
||||
low = mid + 1
|
||||
else:
|
||||
high = mid - 1
|
||||
|
||||
return False
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def solution():
|
||||
return Solution()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"nums, target, expected",
|
||||
[
|
||||
# ([2, 5, 6, 0, 0, 1, 2], 0, True),
|
||||
# ([2, 5, 6, 0, 0, 1, 2], 3, False),
|
||||
([1, 0, 1, 1, 1], 0, True),
|
||||
],
|
||||
)
|
||||
def test_search(solution: Solution, nums: list[int], target: int, expected: bool):
|
||||
assert solution.search(nums, target) == expected
|
Loading…
x
Reference in New Issue
Block a user