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