Skip to content

Commit a22e922

Browse files
committed
feat: passed but large numbers timed out
1 parent 2cfb762 commit a22e922

File tree

1 file changed

+29
-6
lines changed
  • construct_target_array_with_multiple_sums/src

1 file changed

+29
-6
lines changed

construct_target_array_with_multiple_sums/src/lib.rs

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,23 +8,40 @@ pub struct Solution {}
88

99
impl<'a> Solution {
1010
pub fn is_possible(target: Vec<i32>) -> bool {
11+
if target.len() == 1 {
12+
match target.iter().nth(0) {
13+
Some(1) => return true,
14+
_ => return false,
15+
}
16+
}
1117
let mut heap = BinaryHeap::new();
1218
let mut sum = 0;
1319
for e in target.iter() {
1420
heap.push(*e);
1521
sum += e;
1622
}
1723
loop {
18-
let max = heap.pop().unwrap();
24+
// 提取堆中最大的数字
25+
let mut max = heap.pop().unwrap();
1926
if max == 1 {
2027
return true;
2128
}
22-
let stuff = 2 * max - sum;
23-
if stuff < 1 {
24-
return false;
29+
let second_max = *heap.peek().unwrap();
30+
loop {
31+
// 处理最大数字直到它不是最大的
32+
let stuff = 2 * max - sum; // 计划插入对象
33+
if stuff < 1 {
34+
return false;
35+
} else if stuff == 1 && second_max == 1 {
36+
return true;
37+
}
38+
sum -= max - stuff;
39+
if stuff < second_max {
40+
heap.push(stuff);
41+
break;
42+
}
43+
max = stuff;
2544
}
26-
sum -= max - stuff;
27-
heap.push(stuff);
2845
}
2946
}
3047
}
@@ -68,4 +85,10 @@ mod test {
6885
let target = vec![1, 1, 61, 9, 17];
6986
assert!(Solution::is_possible(target));
7087
}
88+
89+
#[test]
90+
fn submission_4() {
91+
let target = vec![2];
92+
assert!(!Solution::is_possible(target));
93+
}
7194
}

0 commit comments

Comments
 (0)