LeetCode周赛-从数量最多的堆取走礼物

使用优先队列PriorityQueue进行求解,优先队列会将添加入队列中的元素进行排序,默认递增,可重写排序方法

常用方法:

  • boolean add(object):将指定的元素插入此优先级队列。
  • boolean offer(object):将指定的元素插入此优先级队列。
  • boolean remove(object):从此队列中删除指定元素的单个实例(如果存在)。
  • Object poll():检索并删除此队列的头部,如果此队列为空,则返回null。
  • Object element():检索但不删除此队列的头部,如果此队列为空,则返回null。
  • Object peek():检索但不删除此队列的头部,如果此队列为空,则返回null。
  • void clear():从此优先级队列中删除所有元素。
  • Comparator comparator():返回用于对此队列中的元素进行排序的比较器,如果此队列根据其元素的自然顺序排序,则返回null。
  • boolean contains(Object o):如果此队列包含指定的元素,则返回true。
  • Iterator iterator():返回此队列中元素的迭代器。
  • int size():返回此队列中的元素数。
  • Object [] toArray():返回包含此队列中所有元素的数组。
  • class Solution {
        public long pickGifts(int[] gifts, int k) {
            PriorityQueue priorityQueue = new PriorityQueue<>((a , b) -> b - a);
            for(int x : gifts){
                priorityQueue.add(x);
            }
            while (k-- > 0) {
                Integer temp = priorityQueue.poll();
                temp = (int) Math.sqrt(temp);
                priorityQueue.add(temp);
            }
            long sum = 0;
    //        for (int i : priorityQueue){
    //            sum += i;
    //        }
            while (priorityQueue.size() != 0){
                sum += priorityQueue.poll();
            }
            return sum;
        }
    }

你可能感兴趣的:(Demo,leetcode,java,数据结构)