-
數組中的第K個最大元素
-
快速排序
代碼:
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
k=len(nums)-k
left=0
right= len(nums)-1
while left<right:
j=self.partition(nums,left,right)
if j==k:
break
elif j<k:
left=j+1
else:
right=j-1
return nums[k]
def partition(self,list,p,r):
i=p-1
for j in range(p,r):
if list[j]<=list[r]:
i+=1
list[i],list[j]=list[j],list[i]
list[i+1],list[r]=list[r],list[i+1]
return i+1
2.堆排序:
對於堆排序一般升序採用大頂堆,降序採用小頂堆。本題中想要尋找的第k個最大的元素,自然需要的是升序排序,因此採用大頂堆。當然本題並不是一個純粹的排序,因此並不需要全部排序完成,只需要進行k次交換,即可找到第k個最大的元素。
https://www.jianshu.com/p/d174f1862601
- 前 K 個高頻元素
代碼:
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
d = {}
for num in nums:
if num in d:
d[num] += 1
else:
d[num] = 1
return [x[0] for x in sorted(d.items(), reverse = True, key=lambda d:d[1])][:k]
- 有序矩陣中第K小的元素
class Solution(object):
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
n, m = len(matrix), len(matrix[0])
l, h = matrix[0][0], matrix[n-1][m-1]
while l < h:
count = 0
mid = l + (h-l)//2
for i in range(n):
j = m-1
while j>=0 and matrix[i][j]>mid:
j -= 1
count += j+1
#print(count, k)
if count>=k:
h = mid
else:
l = mid + 1
return l
- 最少移動次數使數組元素相等 II
代碼:朝着中位數的方向移動
class Solution(object):
def minMoves2(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums=sorted(nums)
res=0
left,right=0,len(nums)-1
while left <right:
res+=nums[right]-nums[left]
left+=1
right-=1
return res
- 最長迴文串
代碼:
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
dict={}
for c in s:
if c in dict:
dict[c] +=1
else:
dict[c]=1
res=0
for value in dict.values():
res+=value/2*2
if res<len(s):
return res+1
return res