mybloger

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

71、柱状图中最大矩形

给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。

求在该柱状图中,能够勾勒出来的矩形的最大面积。

示例 1:

img

输入: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;
    }
}
posted on 2025-08-17 22:24  万能包哥  阅读(13)  评论(0)    收藏  举报