leetcode-1046-最后一块石头的重量

[题目描述]

  1. 有一堆石头,每块石头的重量都是正整数。
  2. 每一回合,从中选出两块 最重的 石头,然后将它们一起粉碎。假设石头的重量分别为 x y,且 x <= y。那么粉碎的可能结果如下:
  3. 如果 x == y,那么两块石头都会被完全粉碎;
  4. 如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x
  5. 最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0
  6. 示例:
  7. 输入:[2,7,4,1,8,1]
  8. 输出:1
  9. 解释:
  10. 先选出 7 8,得到 1,所以数组转换为 [2,4,1,1,1],
  11. 再选出 2 4,得到 2,所以数组转换为 [2,1,1,1],
  12. 接着是 2 1,得到 1,所以数组转换为 [1,1,1],
  13. 最后选出 1 1,得到 0,最终数组转换为 [1],这就是最后剩下那块石头的重量。
  14. 提示:
  15. 1 <= stones.length <= 30
  16. 1 <= stones[i] <= 1000
  17. Related Topics 贪心算法
  18. 👍 164 👎 0

[题目链接]

leetcode题目链接

[相关题目]

leetcode链接: leetcode-1049-最后一颗石头的重量II

本站链接: 每日一题系列

[github地址]

代码链接

[思路介绍]

思路一:暴力法

  • 每一次都对数组做一次排序
  • 然后取最后两个元素
  • 很幸运的是没有TLE
  1. public int lastStoneWeight(int[] stones) {
  2. int n = stones.length;
  3. //corner case;
  4. if (n ==1){
  5. return stones[0];
  6. }
  7. while (stones[n - 2] != 0) {
  8. Arrays.sort(stones);
  9. stones[n - 1] = stones[n - 1] - stones[n - 2];
  10. stones[n - 2] = 0;
  11. Arrays.sort(stones);
  12. }
  13. return stones[n - 1];
  14. }

时间复杂度O(nnlgn)


思路二:最大堆

  • 维护一个堆结构,然后所有元素入堆
  • 每次取两个压一个
  1. public int lastStoneWeight(int[] stones) {
  2. //corner case
  3. PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(
  4. new Comparator<Integer>() {
  5. @Override
  6. public int compare(Integer o1, Integer o2) {
  7. return o2-o1;
  8. }
  9. }
  10. );
  11. for (int i: stones
  12. ) {
  13. priorityQueue.add(i);
  14. }
  15. while (priorityQueue.size() > 1){
  16. int large = priorityQueue.poll();
  17. int small = priorityQueue.poll();
  18. priorityQueue.add(large - small);
  19. }
  20. return priorityQueue.poll();
  21. }

**时间复杂度O(nlgn)