Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitb9b93d8

Browse files
refactor 1354
1 parent0e8724f commitb9b93d8

File tree

1 file changed

+14
-19
lines changed

1 file changed

+14
-19
lines changed
Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,30 @@
11
packagecom.fishercoder.solutions;
22

3-
importjava.util.Collections;
43
importjava.util.PriorityQueue;
54

65
publicclass_1354 {
76
publicstaticclassSolution1 {
87
/**
9-
* 1. A good idea/trick to calculate the previous value of the largest number max: (2 * max - total).
10-
* 2. Use a PriorityQueue to store the elements in reverse order to help us get the largest element in O(1) time
11-
* 3. Also keep a variable of total sum
12-
* <p>
13-
* reference: https://leetcode.com/problems/construct-target-array-with-multiple-sums/discuss/510214/C%2B%2B-Reaching-Points-Work-Backwards
8+
* Use % is the key here to avoid TLE, a good test case for this is [1,1000000000]
149
*/
1510
publicbooleanisPossible(int[]target) {
16-
PriorityQueue<Long>pq =newPriorityQueue<>(Collections.reverseOrder());
17-
longsum =0L;
18-
for (intv :target) {
19-
sum +=v;
20-
pq.offer((long)v);
11+
longsum =0;
12+
PriorityQueue<Integer>maxHeap =newPriorityQueue<>((a,b) ->b -a);
13+
for (inti =0;i <target.length;i++) {
14+
maxHeap.offer(target[i]);
15+
sum +=target[i];
2116
}
22-
while (sum >pq.size()) {
23-
longmax =pq.poll();
24-
Longprev =2 *max -sum;
25-
if (prev <1) {
17+
while (maxHeap.peek() !=1) {
18+
intmax =maxHeap.poll();
19+
sum -=max;
20+
if (max <=sum ||sum <1) {
2621
returnfalse;
2722
}
28-
pq.offer(prev);
29-
sum-=max;
30-
sum +=prev;
23+
max %=sum;
24+
sum+=max;
25+
maxHeap.offer(max);
3126
}
32-
returnsum ==pq.size();
27+
returntrue;
3328
}
3429
}
3530
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp