659. Split Array into Consecutive Subsequences

659. Split Array into Consecutive Subsequences

Question

You are given an integer array nums that is sorted in non-decreasing order.

Determine if it is possible to split nums into one or more subsequences such that both of the following conditions are true:

  • Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer).
  • All subsequences have a length of 3** or more**.

Return true* if you can split nums according to the above conditions, or false otherwise*.

A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [<u>1</u>,2,<u>3</u>,4,<u>5</u>] while [1,3,2] is not).

Solution

用优先级队列储存每个可组成的列表。
优先级队列根据列表的长度排列。

用哈希表记录每个列表的尾数,和其对应的优先级队列。
遍历所有数字,如果存在当前数字num-1为尾数的队列,则获取长度最小的列表,并添加当前数字num在列表中。
然后将新的优先级队列放入哈希表中。

遍历整个哈希表中的数组,如果有数组的长度小于3,则返回false,否则返回true。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public boolean isPossible(int[] nums) {
HashMap<Integer, PriorityQueue<List<Integer>>> map = new HashMap<>();

for(int num : nums){
PriorityQueue<List<Integer>> last = map.getOrDefault(num - 1, null);
PriorityQueue<List<Integer>> curr = map.getOrDefault(num, new PriorityQueue<List<Integer>>((a,b) -> a.size() - b.size()));

if(last == null || last.size() == 0){
List<Integer> arr = new ArrayList<>();
arr.add(num);
curr.add(arr);
map.put(num, curr);
}
else{
List<Integer> arr = last.poll();
arr.add(num);
curr.add(arr);
map.put(num, curr);
}
}

for(int last : map.keySet()){
for(List<Integer> arr : map.get(last)){
if(arr.size() < 3) return false;
}
}
return true;

}
}

Solution 2

不需要保存整个列表,只需要保存对应末尾数字的列表长度即可。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public boolean isPossible(int[] nums) {
HashMap<Integer, PriorityQueue<Integer>> map = new HashMap<>();

for(int num : nums){
PriorityQueue<Integer> last = map.getOrDefault(num - 1, null);
PriorityQueue<Integer> curr = map.getOrDefault(num, new PriorityQueue<Integer>());

if(last == null || last.size() == 0){
curr.add(1);
map.put(num, curr);
}
else{
int min = last.poll();
curr.add(min+1);
map.put(num, curr);
}
}

for(int last : map.keySet()){
for(int len : map.get(last)){
if(len < 3) return false;
}
}
return true;

}
}
630. Course Schedule III

630. Course Schedule III

Question

There are n different online courses numbered from 1 to n. You are given an array courses where courses[i] = [duration<sub>i</sub>, lastDay<sub>i</sub>] indicate that the i<sup>th</sup> course should be taken continuously for duration<sub>i</sub> days and must be finished before or on lastDay<sub>i</sub>.

You will start on the 1<sup>st</sup> day and you cannot take two or more courses simultaneously.

Return the maximum number of courses that you can take.

Solution

贪心算法,优先级队列实现。
优先选择截止日期更短的课程。
优先级队列pq记录当前已选课程,按持续时间从长到短排列。
同时维护当前的日期curDay。

当当前选择的课程截止日期晚于curDay加上当前的持续时间duration时,查看大根堆里最长的课程longestDuration。如果最长的时间大于当前时间,则将其挤出,并将当前课程加入。

如果当前课程截止日期晚于curDay,则直接将其加入队列中,并更新curDay。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public int scheduleCourse(int[][] courses) {
Arrays.sort(courses, (a, b) -> a[1] - b[1]);
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[0] - a[0]);
int curDay = 0;
for(int[] course : courses){
int duration = course[0];
int lastDay = course[1];

if(curDay + duration > lastDay){ //大于截止日期
if(pq.isEmpty()) continue;
int longestDuration = pq.peek()[0];
if(longestDuration > duration){ //替换到当前队列中持续日期最长的课程
curDay -= pq.poll()[0];
curDay += duration;
pq.offer(course);
}
}
else{ //小于截止日期则加入选课
curDay += duration;
pq.offer(course);
}
}
return pq.size();
}
}
1354. Construct Target Array With Multiple Sums

1354. Construct Target Array With Multiple Sums

Question

You are given an array target of n integers. From a starting array arr consisting of n 1’s, you may perform the following procedure :

  • let x be the sum of all elements currently in your array.
  • choose index i, such that 0 <= i < n and set the value of arr at index i to x.
  • You may repeat this procedure as many times as needed.

Return true if it is possible to construct the target array from arr, otherwise, return false.

Solution 1

递归,每次寻找到数组中最大的数字的下标maxIndex,并对整个数组加和。
当数组中出现小于1的数时,不成立,返回false。
当数组加和等于数组长度时,返回true。

记录剩余的数字others,如果没有剩余数字,则返回false。
将target[maxIndex]减去others,因此每次翻倍,快速逼近。
当小于0时,则还原到上一个target[maxIndex]。

递归更改后的数组。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public boolean isPossible(int[] target) {
int maxIndex = 0, sum = 0;
for(int i = 0; i < target.length; i++){
if(target[i] <= 0) return false; //数组中出现小于1的数,则不成立,返回false
if(target[maxIndex] < target[i]) maxIndex = i;
sum += target[i];
}
if(sum == target.length) return true; //加和等于长度,则数组内全部为1,返回true
int others = sum - target[maxIndex];
if(others == 0) return false; //没有其他值时返回false
target[maxIndex] -= others;
int n = 1;
while(target[maxIndex] > others){
target[maxIndex] -= n * others;
if(target[maxIndex] <= 0){
target[maxIndex] += n * others;
break;
}
n*=2; //因子每次翻倍,快速逼近
}
return isPossible(target);
}
}

Solution 2

优先级队列, 大根堆。
每次挤出队列里最大的数字max。

如果max的值为1,则返回true。

计算加和和新的值,并更新sum。
如果最大的数字max小于0,或者剩余的sum小于0,则返回false。

当max仍然大于剩下的数字时,继续做减法。采用因数翻倍,快速接近目标值。
如果max小于0,则恢复到上一个值,并添加到优先级队列中。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public boolean isPossible(int[] target) {
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
int sum = 0;
for(int num : target){
pq.offer(num);
sum+=num;
}
while(true){
int max = pq.poll();
if(max == 1) return true;

sum -= max;
max = max - sum;
if(sum <= 0 || max <= 0) return false;

int n = 1;
while(max > sum){
max -= n * sum;
if(max <= 0){
max += n * sum;
break;
}
n*=2;
}
sum += max;
pq.offer(max);
}
}
}
1642. Furthest Building You Can Reach

1642. Furthest Building You Can Reach

Question

You are given an integer array heights representing the heights of buildings, some bricks, and some ladders.

You start your journey from building 0 and move to the next building by possibly using bricks or ladders.

While moving from building i to building i+1 (0-indexed),

  • If the current building’s height is greater than or equal to the next building’s height, you do not need a ladder or bricks.

  • If the current building’s height is less than the next building’s height, you can either use one ladder or (h[i+1] - h[i]) bricks.

Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.

Solution

贪心算法+优先级队列。

从第二栋楼开始遍历当前位置,下一栋楼与当前位置的高度差为h。
如果h小于0,则无成本前进。
否则如果剩余砖块,则优先使用砖块,并将使用砖块的个数加入大根堆中。
如果剩余砖块不足,且有梯子剩余时,用梯子替换掉小号最多砖块的位置,增加剩余砖块的数量。
如果剩余砖块和梯子都不足,则返回上一个位置。

如果遍历到最后,则返回最后一个建筑物的位置。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int furthestBuilding(int[] heights, int bricks, int ladders) {
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for(int i = 1; i < heights.length; i++){
int h = heights[i] - heights[i-1];
if(h > 0){
pq.add(h);
bricks-=h;
if(bricks < 0){
if(ladders > 0){
ladders--;
bricks += pq.poll();
}
else{
return i-1;
}
}
}
}
return heights.length - 1;
}
}
743. Network Delay Time

743. Network Delay Time

Question

You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (u<sub>i</sub>, v<sub>i</sub>, w<sub>i</sub>), where u<sub>i</sub> is the source node, v<sub>i</sub> is the target node, and w<sub>i</sub> is the time it takes for a signal to travel from source to target.

We will send a signal from a given node k. Return the time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.

Solution

Dijkstra算法

此题可以转化为求起始节点到最远距离的节点的距离。单源最短路径问题,可以采用Dijkstra算法。

采用一个visited[]数组记录初始节点的访问状况。
同时dist[]数组记录到达这一节点的最小距离,初始化为无限大。

进行BFS搜索,每次优先访问当前节点的子节点的最近子节点,并更新子节点与初始节点距离。
最后遍历dist[]数组,如果有元素仍为无限大,则BFS搜索未遍历到,返回-1。
否则返回数组内最大的距离即可。

建立映射

首先通过哈希表,将起始节点与有向边建立起映射关系。列表中储存子节点和对应边上的权值。
注意由于index是-1的,因此在组成列表时需要将当前数字减一。

优先级队列

采用优先级队列组成小根堆,每次将当前的最小距离作为权值加入队列。
初始化队列时需要将起始节点(k-1)放入,此时的总距离为0。

当当前的子节点的cost加上起始节点的距离小于子节点的最小距离时,更新子节点最小距离。
同时将子节点当前最小距离作为比较对象传入优先级队列。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
public int networkDelayTime(int[][] times, int n, int k) {
HashMap<Integer, List<int[]>> edges = new HashMap<>();

for(int[] time : times){ //建立有向边
int source = time[0] - 1, kid = time[1] - 1, cost = time[2]; //注意index需要-1
List<int[]> list = edges.getOrDefault(source, new ArrayList<>());
list.add(new int[]{kid, cost}); //建立起点——终点映射
edges.put(source, list);
}

int[] visited = new int[n];
int[] dist = new int[n];
Arrays.fill(dist, Integer.MAX_VALUE);

PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> a[1] - b[1]); //优先级队列,最小堆每次访问距离最近的节点

int start = k-1;
dist[start] = 0;
pq.offer(new int[]{start, 0}); //start为初始节点,后面的距离为了实现优先级队列

while(!pq.isEmpty()){
int[] curr = pq.poll();
int source = curr[0];

if(visited[source] == 1) continue;
visited[source] = 1;

List<int[]> children = edges.getOrDefault(source, new ArrayList<>()); //获取当前起点的所有边
for(int[] child : children){
int kid = child[0], cost = child[1];

if(cost + dist[source] < dist[kid]){ //如果新的距离小于之前的最小距离,则更新距离并将新的起点加入优先级队列
dist[kid] = cost + dist[source];
pq.offer(new int[]{kid, dist[kid]}); //更新的距离是从出发节点到当前节点的距离,每次优先访问最近的节点
}
}
}

int res = 0;

for(int d : dist){ //最后遍历,距离的最大值就是结果
res = Math.max(res, d);
}
return res == Integer.MAX_VALUE ? -1 : res;
}
}
973. K Closest Points to Origin

973. K Closest Points to Origin

Question

Given an array of points where points[i] = [x<sub>i</sub>, y<sub>i</sub>] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).

The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x<sub>1</sub><span> </span>- x<sub>2</sub>)<sup>2</sup><span> </span>+ (y<sub>1</sub><span> </span>- y<sub>2</sub>)<sup>2</sup>).

You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).

Solution

此题可以采用快速排序的思想。可以在O(n)时间复杂度里完成排序。

Solution 2

优先级队列,根据每个点距离的平方排序。时间复杂度O(nlogk)。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int[][] kClosest(int[][] points, int k) {
int[][] ret = new int[k][2];
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> squaredDistance(a) - squaredDistance(b));
for(int[] point : points){
pq.add(point);
}
for(int i = 0; i < k; i++){
ret[i] = pq.poll();
}
return ret;
}

private int squaredDistance(int[] point){
int x = point[0], y = point[1];
return x * x + y * y;
}
}

Solution 3

直接排序。时间复杂度为O(nlogn)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int[][] kClosest(int[][] points, int k) {
int[][] ret = new int[k][2];
Arrays.sort(points, (a, b) -> squaredDistance(a) - squaredDistance(b));
for(int i = 0; i < k; i++){
ret[i] = points[i];
}
return ret;
}

private int squaredDistance(int[] point){
int x = point[0], y = point[1];
return x * x + y * y;
}
}
451. Sort Characters By Frequency

451. Sort Characters By Frequency

Question

Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.

Return the sorted string. If there are multiple answers, return any of them.

Solution

哈希表记录字符出现的频率。然后将其添加到优先队列中。
最后根据优先级队列的顺序,加入每个字符对应的哈希表中记录的字符数。
理论上也可以用数组记录频率,但是问题中字符较复杂故未采用。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public String frequencySort(String s) {
HashMap<Character, Integer> map = new HashMap<>();
PriorityQueue<Character> pq = new PriorityQueue<>((a,b) -> map.get(b) - map.get(a));
StringBuffer sb = new StringBuffer();
for(char c : s.toCharArray()){
map.put(c, map.getOrDefault(c, 0)+1);
}
for(char c : map.keySet()){
pq.add(c);
}
while(!pq.isEmpty()){
char c = pq.poll();
for(int i = 0; i < map.get(c); i++){
sb.append(c);
}
}
return sb.toString();
}
}
215. Kth Largest Element in an Array

215. Kth Largest Element in an Array

Problem

Given an integer array nums and an integer k, return the k<sup>th</sup> largest element in the array.

Note that it is the k<sup>th</sup> largest element in the sorted order, not the k<sup>th</sup> distinct element.

Solution

直接排序数组,返回倒数第k个值。

Code

1
2
3
4
5
6
class Solution {
public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums);
return nums[nums.length - k];
}
}

Solution 2

采用优先级队列,将所有元素加入队列,采用倒序比较器。
挤出前k-1个值,然后返回第k个值。

Code

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for(int num : nums){
pq.add(num);
}
for(int i = 0; i < k-1; i++){
pq.poll();
}
return pq.peek();
}
}

155. Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Implement the MinStack class:

  • MinStack() initializes the stack object.
  • void push(int val) pushes the element val onto the stack.
  • void pop() removes the element on the top of the stack.
  • int top() gets the top element of the stack.
  • int getMin() retrieves the minimum element in the stack.

分别将数据保存在一个Priority Queue和一个栈中。
pop方法pop掉stack的内容,然后将其从优先队列中移除。
top方法返回stack的栈顶。
getMin方法返回优先队列的顶。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class MinStack {
Queue<Integer> pq;
Stack<Integer> stack;
public MinStack() {
pq = new PriorityQueue<>();
stack = new Stack<>();
}

public void push(int val) {
pq.add(val);
stack.add(val);
}

public void pop() {
int i = stack.pop();
pq.remove(i);

}

public int top() {
return stack.peek();
}

public int getMin() {
return pq.peek();
}
}

/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/

1631. Path With Minimum Effort

You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.

A route’s effort is the maximum absolute difference in heights between two consecutive cells of the route.

Return the minimum effort required to travel from the top-left cell to the bottom-right cell.

A*算法,启发式搜索。BFS搜索结合Priority Queue。
采用一个数组储存当前访问点的位置,以及其effort。
采用优先队列,优先搜索effort最小的方向。
每次循环倾倒出队列中所有的元素。
计算上一个节点和当前节点的差值作为nextEffort,并和上一个节点的effort作比较,较大的作为当前节点的effort,
将effort作为权重,优先搜索一个层级内effort较小的路径。
将所有操作加入队列,并排除越界的位置。
当当前节点为最后一个节点时,返回其effort。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
int min;
public int minimumEffortPath(int[][] heights) {
int[][] operations = {{1,0},{-1,0},{0,1},{0,-1}};
int m = heights.length, n = heights[0].length;

Queue<int[]> q = new PriorityQueue<>((a, b) -> a[2] - b[2]);
int[] point = {0, 0, 0};
int size = 1;
int[][] visited = new int[m][n];

q.add(point);
while(!q.isEmpty()){

for(int k = 0; k < size; k++){
int[] curr = q.poll();
int i = curr[0], j = curr[1], currEffort = curr[2];
if(visited[i][j] == 1) continue;
visited[i][j] = 1;
if(i == m-1 && j == n-1) return currEffort;
for(int[] operation : operations){
int nextX = i + operation[0];
int nextY = j + operation[1];
if(nextX < 0 || nextY < 0 || nextX >= m || nextY >= n) continue;
int nextEffort = Math.max(currEffort, Math.abs(heights[i][j] - heights[nextX][nextY]));
int[] next = {nextX, nextY, nextEffort};

q.add(next);
}
}
size = q.size();
}
return -1;
}
}

1202. Smallest String With Swaps

You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.

You can swap the characters at any pair of indices in the given pairs any number of times.

Return the lexicographically smallest string that s can be changed to after using the swaps.

并查集,注意要使用路径压缩否则会超时。
先将所有配对联通。然后创建一个数组group记录每个字符串位置的分组情况。
根据分组,借助优先队列保存字符串。
通过哈希表创建group和PriorityQueue的映射。
按当前位置的分组情况和优先队列的顺序来添加字符串。
最后返回字符串。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Solution {
public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {
StringBuffer sb = new StringBuffer();
UnionFind uf = new UnionFind(s.length());

for(List<Integer> pair : pairs){
uf.union(pair.get(0), pair.get(1));
}

int[] group = new int[s.length()];
for(int i = 0; i < s.length(); i++){
group[i] = uf.find(i);
}

HashMap<Integer, PriorityQueue<Character>> map = new HashMap<>();

for(int i = 0; i < s.length(); i++){
PriorityQueue<Character> bin = map.getOrDefault(group[i], new PriorityQueue<Character>());
bin.add(s.charAt(i));
map.put(group[i], bin);
}
for(int i = 0; i < s.length(); i++){
sb.append(map.get(group[i]).poll());
}
return sb.toString();
}

class UnionFind {
int[] parent;
int[] count;
public UnionFind(int n){
parent = new int[n];
count = new int[n];
for(int i = 0; i < n; i++){
parent[i] = i;
count[i] = 1;
}
}

private int find(int id){
if(parent[id] == id) return id;
parent[id] = find(parent[id]);
return parent[id];
}

private boolean union(int id1, int id2){
int p1 = find(id1);
int p2 = find(id2);
if(p1 == p2) return false;
if(count[p1] > count[p2]) parent[p2] = p1;
else parent[p1] = p2;
return true;
}
}
}

347. Top K Frequent Elements

Question

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Solution

遍历,使用哈希表保存遍历次数。
再次遍历,根据元素出现的次数将其填入优先级队列实现的大根堆。
遍历取出k个最大值。

  • getOrDefault():
    方便的遍历并生成哈希表。
  • lambda:
    ()内表示传入的数值。
    -> 后表示返回值。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int[] topKFrequent(int[] nums, int k) {
int[] ans = new int[k];
HashMap<Integer,Integer> map = new HashMap();
for (int num : nums){
map.put( num, map.getOrDefault(num , 0) + 1 );
}
PriorityQueue<Integer> pq = new PriorityQueue((a,b) -> map.get(b) - map.get(a));
for (int key : map.keySet()){
pq.add(key);
}
for (int i = 0; i < k ; i++){
ans[i] = pq.poll();
}
return ans;
}
}

703. Kth Largest Element in a Stream

问题
Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Implement KthLargest class:

  • KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
  • int add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream.

优先级队列,插入所有元素,小元素在前。
当队列长度大于k时,poll掉前面的元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class KthLargest {
PriorityQueue<Integer> pq;
int kth;
public KthLargest(int k, int[] nums) {
pq = new PriorityQueue<Integer>();
kth = k;
for (int num : nums){
pq.add(num);
}
}

public int add(int val) {
pq.add(val);
while (pq.size() > kth){
pq.poll();
}
return pq.peek();
}
}

/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.add(val);
*/

1046. Last Stone Weight

问题
You are given an array of integers stones where stones[i] is the weight of the ith stone.

We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is:

  • If x == y, both stones are destroyed, and
  • If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.
    At the end of the game, there is at most one stone left.

Return the smallest possible weight of the left stone. If there are no stones left, return 0.

采用PriorityQueue队列,将所有元素放入。
每次取出两个,将两者的差值放回队列。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(Collections.reverseOrder());
for (int stone : stones){
pq.add(stone);
}

while ( pq.size() > 1) {
int largeStone = pq.poll();
int smallStone = pq.poll();
pq.add( largeStone - smallStone );
}

return pq.poll();
}
}