169. 多数元素
我用的就是字典,哈希
python
class Solution:
def majorityElement(self, nums: List[int]) -> int:
cnt=dict()
n=len(nums)
for num in nums:
if num in cnt:
cnt[num]+=1
else:
cnt[num]=1
for num in cnt:
if cnt[num]>n/2:
return num
排序也可以,第n/2下取整位置上的是众数 O(nlogn),空间复杂度可以降低到O(logn),自写堆排序降低到O(1)
python
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums.sort()
return nums[len(nums) // 2]
分治法
python
class Solution:
def majorityElement(self, nums: List[int]) -> int:
def majority_element_rec(lo, hi) -> int:
# base case; the only element in an array of size 1 is the majority
# element.
if lo == hi:
return nums[lo]
# recurse on left and right halves of this slice.
mid = (hi - lo) // 2 + lo
left = majority_element_rec(lo, mid)
right = majority_element_rec(mid + 1, hi)
# if the two halves agree on the majority element, return it.
if left == right:
return left
# otherwise, count each element and return the "winner".
left_count = sum(1 for i in range(lo, hi + 1) if nums[i] == left)
right_count = sum(1 for i in range(lo, hi + 1) if nums[i] == right)
return left if left_count > right_count else right
return majority_element_rec(0, len(nums) - 1)
随机法是搞笑的吧。。
还有Boyer-Moore 投票算法,妙
160.相交链表
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
#先把数字都拿出来,倒着找到数字一样的最后一个,然后把指针指过来看是不是同一个节点,如果不是就双指针++
lista=[]
listb=[]
p=headA
while p!=None:
lista.append(p.val)
p=p.next
p=headB
while p!=None:
listb.append(p.val)
p=p.next
lena=len(lista)
lenb=len(listb)
i=lena-1
j=lenb-1
while i>=1 and j>=1:
if lista[i]==listb[j]:
i-=1
j-=1
else:
break
p=headA
for cnt in range(0,i):
p=p.next
q=headB
for cnt in range(0,j):
q=q.next
while p!=q:
p=p.next
q=q.next
return p
哈希更好
然后双指针更天才,算法天才,想不到
评论有人说,让长的先走s步,s是多的长度,感觉也可以
206.反转链表
O(n)
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head!=None:
p=head
q=p.next
while q!=None :
r=q.next
if p==head:
p.next=None
q.next=p
p=q
q=r
head=p
return head
那个递归思考量有点大,看着答案都想了半天,而且占空间还多。