Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:
Solution
class Solution(object):
def topKFrequent(self, nums, k):
from collections import Counter
import heapq
c = Counter(nums)
return heapq.nlargest(k, c.keys(), key = c.get)
Solution
from collections import Counter
class Solution:
def topKFrequent(self, nums, k):
c = Counter(nums)
h = []
res = []
for v,f in c.items():
if len(h) < k:
heapq.heappush(h, (f, v))
else:
heapq.heappushpop(h, (f, v))
for i in range(k):
res.append(h[i][1])
return res
nlogk
Kth Largest Element in an Array
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note: You may assume k is always valid, 1 ≤ k ≤ array's length.
Solution:
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
if not nums: return 0
h = []
for i in range(len(nums)):
if len(h) < k:
heapq.heappush(h, nums[i])
else:
heapq.heappushpop(h, nums[i])
return h[0]
nlogk
Solution - 二分搜索
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
if k>len(nums): return None
l, r = [], []
for i in range(1, len(nums)):
if nums[i] > nums[0]: r.append(nums[i])
elif nums[i] <= nums[0]: l.append(nums[i])
if len(r)+1 == k: return nums[0]
elif len(r)>=k : return self.findKthLargest(r, k)
else: return self.findKthLargest(l, k-len(r)-1)
return None
Kth Smallest Element in a Sorted Matrix
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 13.
Note: You may assume k is always valid, 1 ≤ k ≤ n2.
Solution:
暴力排序(nlogn) -> 最大堆(nlogk) ->二分法nlogk
klogk: 一次添加右和下,pop出其中较小的,每次pop k-1,pop k次返回
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
row, col = len(matrix), len(matrix[0])
h = [(matrix[0][0], 0, 0)]
res = 0
visited = set((0,0))
while k > 0:
res, r, c = h.pop()
if r+1 < row and (r+1,c) not in visited:
heapq.heappush(h, (matrix[r+1][c], r+1, c))
visited.add((r+1,c))
if c+1 < col and (r,c+1) not in visited:
heapq.heappush(h, (matrix[r][c+1], r, c+1))
visited.add((r,c+1))
k -= 1
return res
nlogk
计算最大值和最小值的平均值,count_num算出小于该平均值的个数,个数大于小于k决定了left和right的变化(本质上反映了target的变化)
class Solution(object):
def kthSmallest(self, matrix, k):
# 计算小于等于目标值的元素个数,根据递增规则,从右上角开始查找
def count_num(m, target):
i = 0
j = len(m) - 1
ans = 0
while i < len(m) and j >= 0:
if m[i][j] <= target:
ans += j + 1
i += 1
else:
j -= 1
return ans
# 思路:左上角元素最小,右下角元素最大,计算小于等于中间值的元素个数
left = matrix[0][0]
right = matrix[-1][-1]
# 二分法查找
while left < right:
mid = (left + right) >> 1
# print(' mid = ', mid)
count = count_num(matrix, mid)
# print('count = ', count)
if count < k:
left = mid + 1
else:
right = mid
return left
A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B).
添加描述
The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi], where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX, 0 < Hi ≤ INT_MAX, and Ri - Li > 0. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.
For instance, the dimensions of all buildings in Figure A are recorded as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] .
The output is a list of "key points" (red dots in Figure B) in the format of [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely defines a skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should be considered part of the skyline contour.
For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].
Notes:
Solution:
ab
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。