【leetcode】排序1122、242、56、493
阿新 • • 發佈:2021-02-13
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
dic = {b:i for i, b in enumerate(arr2)}
return sorted(arr1, key = lambda a:dic.get(a, a + 1000))
242. 有效的字母異位詞
**字母異位詞:**即為各個字母的數目相同,而順序不一致。
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# 計數排序,就是統計每個字母出現了多少次,如果出現的次數是一樣的話就是異位詞
return collections.Counter(s) == collections.Counter(t)
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key = lambda x: x[0])
merged =[]
for i in intervals:
# if the list of merged intervals is empty
# or if the current interval does not overlap with the previous,
# simply append it.
# 如果合併的列表 merged 是空的,可以新增或者新的陣列沒有和 merged 發生重疊,直接新增, 如果發生重疊,需要進行邊界的擴充套件
if not merged or merged[-1][-1] < i[0]:
merged.append(i)
# otherwise, there is overlap,
#so we merge the current and previous intervals.
else:
merged[-1][-1] = max(merged[-1][-1], i[-1])
return merged
493. 翻轉對
**逆序對:**i 小於 j,但是nums[ i ]大於nums[ j ]
大致有三種方法,如下:
class Solution(object):
def __init__(self):
self.cnt = 0
def reversePairs(self, nums):
def msort(lst):
# merge sort body
L = len(lst)
if L <= 1: # base case
return lst
else: # recursive case
return merger(msort(lst[:int(L/2)]), msort(lst[int(L/2):]))
def merger(left, right):
# merger
l, r = 0, 0 # increase l and r iteratively
while l < len(left) and r < len(right):
if left[l] <= 2*right[r]:
l += 1
else:
self.cnt += len(left)-l # add here
r += 1
return sorted(left+right) # I can't avoid TLE without timsort...
msort(nums)
return self.cnt