1523. Count Odd Numbers in an Interval Range (easy)
class Solution:
def countOdds(self, low: int, high: int) -> int:
# 2 to 4 : 1
# 3 to 5 : 2
# 2 to 5 : 2
res = (high - low) // 2
if high % 2 == 1 or low % 2 == 1:
res += 1
return res
141. Linked List Cycle (easy)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
target = head
nodes = set()
while target:
target = target.next
if target in nodes:
return True
nodes.add(target)
return False
21. Merge Two Sorted Lists (easy)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
merge = ListNode(0)
cur = merge
while list1 and list2:
if list1.val < list2.val:
cur.next = ListNode(list1.val)
list1 = list1.next
else:
cur.next = ListNode(list2.val)
list2 = list2.next
cur = cur.next
if list1:
cur.next = list1
if list2:
cur.next = list2
return merge.next
203. Remove Linked List Elements (easy)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
temp = ListNode(0)
point = temp
cur = head
while cur:
if cur.val != val:
point.next = ListNode(cur.val)
point = point.next
cur = cur.next
return temp.next
81. Search in Rotated Sorted Array II (medium)
class Solution:
def search(self, nums: List[int], target: int) -> bool:
if not nums: return False
def dfs(l, r):
if l >= r: return False
mid = l + (r - l) // 2
if nums[mid] == target: return True
if nums[mid] == nums[l] and nums[l] == nums[r-1]:
return dfs(l, mid) or dfs(mid+1, r)
if nums[mid] >= nums[l]:
return dfs(l, mid) if nums[l] <= target < nums[mid] else dfs(mid+1, r)
else:
return dfs(mid+1, r) if nums[mid] < target <= nums[r-1] else dfs(l, mid)
return dfs(0, len(nums))