版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Sengo_GWU/article/details/82470496
347. Top K Frequent Elements
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
d, q = {}, {}
for n in nums:
if d.get(n) is None:
d[n] = 1
else:
d[n] += 1
for n, c in d.items():
if q.get(c) is None:
q[c] = [n]
else:
q[c].append(n)
res = []
for i in xrange(len(nums), 0, -1):
if k < 0:
break
elif q.get(i):
res += [q[i][s] for s in xrange(min(k, len(q[i])))]
k -= len(q[i])
return res
454. 4Sum II
第一次解法O(n^2),但是Memory Limit Exceeded
class Solution(object):
def fourSumCount(self, A, B, C, D):
"""
:type A: List[int]
:type B: List[int]
:type C: List[int]
:type D: List[int]
:rtype: int
"""
n, res = len(A), 0
mapAB = collections.defaultdict(list)
for i in xrange(n):
for j in xrange(n):
Sum = A[i] + B[j]
mapAB[Sum].append([i, j])
for i in xrange(n):
for j in xrange(n):
Sum = C[i] + D[j]
res += len(mapAB[0-Sum])
return res
稍稍修改了下:
class Solution(object):
def fourSumCount(self, A, B, C, D):
"""
:type A: List[int]
:type B: List[int]
:type C: List[int]
:type D: List[int]
:rtype: int
"""
n, res = len(A), 0
mapAB = collections.defaultdict(int)
for i in xrange(n):
for j in xrange(n):
Sum = A[i] + B[j]
mapAB[Sum] += 1
for i in xrange(n):
for j in xrange(n):
Sum = C[i] + D[j]
res += mapAB[0-Sum]
return res
138. Copy List with Random Pointer
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
d = dict()
p1 = p2 = head
while p1:
d[p1] = RandomListNode(p1.label)
p1 = p1.next
while p2:
d[p2].next = d.get(p2.next)
d[p2].random = d.get(p2.random)
p2 = p2.next
return d.get(head)