2749. 得到整数零需要执行的最少操作数

This commit is contained in:
li-chx 2025-09-05 11:41:56 +08:00
parent f29016175d
commit dddf4ac7dd
1 changed files with 56 additions and 52 deletions

View File

@ -1,62 +1,66 @@
use std::cmp::min;
struct Solution; struct Solution;
impl Solution { impl Solution {
pub fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> { pub fn make_the_integer_zero(num1: i32, num2: i32) -> i32 {
let mut top_x = 0; fn max_able_contains_two(number: u64) -> i64{
let mut left_y = 0; let mut ans : i64= 0;
let mut bottom_x = matrix.len() as i32 - 1; let mut index = 0;
let mut right_y = matrix[0].len() as i32 - 1; for i in 0..64 {
let mut next_x = 0; if (number >> i) & 1 == 1 {
let mut next_y = 1; ans += 2_i64.pow(index);
let mut pos = (0, 0); }
index += 1;
let mut res = vec![matrix[0][0]]; }
ans
let mut next_pos = || { }
let mut new_pos = (pos.0 + next_x, pos.1 + next_y); fn check(num1: i64, num2: i64, k: i64) -> bool {
if new_pos.0 > bottom_x || new_pos.0 < top_x || new_pos.1 > right_y || new_pos.1 < left_y { let new_num1 = num1 - k * num2;
(next_x, next_y) = match (next_x, next_y) { if new_num1 < 0 {
(0, 1) => { return false;
top_x += 1; }
(1, 0) let max_cnt = max_able_contains_two(new_num1 as u64);
} let min_cnt = new_num1.count_ones() as i64;
(1, 0) => { k >= min_cnt && k <= max_cnt
right_y -= 1; }
(0, -1) let mut l = 0;
} let mut r = 1_000_000_010;
(0, -1) => { let num1 = num1 as i64;
bottom_x -= 1; let num2 = num2 as i64;
(-1, 0) if num2 > 0 {
} r = min(r, num1 / num2);
(-1, 0) => { let mut have_ans = false;
left_y += 1; for i in (0..r + 1).rev() {
(0, 1) if check(num1,num2,i) {
} r = i;
_ => (0, 0), have_ans = true;
}; break;
new_pos = (pos.0 + next_x, pos.1 + next_y);
if new_pos.0 > bottom_x
|| new_pos.0 < top_x
|| new_pos.1 > right_y
|| new_pos.1 < left_y
{
return false;
} }
} }
pos = new_pos; if !have_ans {
res.push(matrix[pos.0 as usize][pos.1 as usize]); return -1;
true }
}; }
while next_pos() {}
res while l < r {
let mid = (l + r) / 2;
if check(num1, num2, mid) {
r = mid;
}else {
l = mid + 1;
}
}
if l == 1_000_000_010 { return -1; }
for i in 1..l + 1 {
if check(num1, num2, i) {
return i as i32;
}
}
-1
} }
} }
fn main() { fn main() {
let sl = Solution::spiral_order(vec![ let sl = Solution::make_the_integer_zero(34,9);
vec![1, 2, 3, 4],
vec![5, 6, 7, 8],
vec![9, 10, 11, 12],
]);
println!("{:?}", sl); println!("{:?}", sl);
} }