71、柱状图中最大矩形
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
示例 1:

输入:heights = [2,1,5,6,2,3]
输出:10
解释:最大的矩形为图中红色区域,面积为 10
class Solution {
public int largestRectangleArea(int[] heights) {
int n = heights.length;
int[] newHeights = new int[n + 2];
System.arraycopy(heights,0,newHeights,1,n);
n+=2;
Deque<Integer> stack = new ArrayDeque<>();
int maxArea = 0;
for (int i = 0;i < n;i++) {
while (!stack.isEmpty() && newHeights[i] < newHeights[stack.peek()]) {
int h = newHeights[stack.pop()];
int w = i - stack.peek() - 1;
maxArea = Math.max(maxArea, h * w);
}
stack.push(i);
}
return maxArea;
}
}
72、数组中的第K个最大元素
给定整数数组 nums 和整数 k,请返回数组中第 **k** 个最大的元素。
请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
你必须设计并实现时间复杂度为 O(n) 的算法解决此问题。
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>();
for (int num : nums) {
heap.offer(num);
if (heap.size() > k) {
heap.poll();
}
}
return heap.peek();
}
}
import java.util.Random;
class Solution {
Random rand = new Random();
// 对外接口
public int findKthLargest(int[] nums, int k) {
// nums.length - k 是因为 quickSelect 按升序 partition
return quickSelect(nums, 0, nums.length - 1, nums.length - k);
}
private int quickSelect(int[] nums, int left, int right, int k) {
if (left == right) return nums[left];
int pivotIndex = left + rand.nextInt(right - left + 1); // 随机选 pivot
swap(nums, pivotIndex, right); // 把 pivot 放到最后,方便 partition
int l = left;
for (int i = left; i < right; i++) {
if (nums[i] < nums[right]) { // partition
swap(nums, l, i);
l++;
}
}
swap(nums, l, right); // pivot 放到最终位置
if (l == k) return nums[l];
else if (l < k) return quickSelect(nums, l + 1, right, k);
else return quickSelect(nums, left, l - 1, k);
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
|
作者:万能包哥 出处:http://www.cnblogs.com/mybloger/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 如果文中有什么错误,欢迎指出。以免更多的人被误导。 |
浙公网安备 33010602011771号