|
|
|
|
# 1590. 使数组和能被 P 整除
|
|
|
|
|
|
|
|
|
|
### description:
|
|
|
|
|
|
|
|
|
|
给你一个长度为 `n` 下标从 **0** 开始的字符串 `blocks` ,`blocks[i]` 要么是 `'W'` 要么是 `'B'` ,表示第 `i` 块的颜色。字符 `'W'` 和 `'B'` 分别表示白色和黑色。给你一个整数 `k` ,表示想要 **连续** 黑色块的数目。每一次操作中,你可以选择一个白色块将它 **涂成** 黑色块。请你返回至少出现 **一次** 连续 `k` 个黑色块的 **最少** 操作次数。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
代码:
|
|
|
|
|
|
|
|
|
|
```rust
|
|
|
|
|
use std::collections::HashMap;
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
let arr:[i32; 4] = [3, 1, 4, 2];
|
|
|
|
|
let nums_vec:Vec<i32> = vec![3, 1, 4, 2];
|
|
|
|
|
let p = 6;
|
|
|
|
|
|
|
|
|
|
let res = min_subarray(&arr, p);
|
|
|
|
|
println!("res1 is: {}", res);
|
|
|
|
|
let res = min_subarray_vector(nums_vec, p);
|
|
|
|
|
println!("res2 is: {}", res);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fn min_subarray(nums:&[i32], p:i32) -> i32{
|
|
|
|
|
let mut x = 0;
|
|
|
|
|
for num in nums {
|
|
|
|
|
x = (x + num) % p;
|
|
|
|
|
}
|
|
|
|
|
if x == 0 {
|
|
|
|
|
return 0;
|
|
|
|
|
}
|
|
|
|
|
let mut index = HashMap::new();
|
|
|
|
|
// let mut y = 0;
|
|
|
|
|
// let mut res = arr.len();
|
|
|
|
|
let (mut y, mut res) = (0, nums.len() as i32);
|
|
|
|
|
|
|
|
|
|
for(i, num) in nums.iter().enumerate(){
|
|
|
|
|
// println!("index is {}, value is {}", i, num);
|
|
|
|
|
index.insert(y, i as i32);
|
|
|
|
|
y = (y + num) % p;
|
|
|
|
|
if let Some(&j) = index.get(&((y - x + p) % p)){
|
|
|
|
|
res = res.min((i as i32 - j) + 1);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if res == nums.len() as i32 {-1} else {res}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fn min_subarray_vector(nums:Vec<i32>, p:i32) -> i32{
|
|
|
|
|
let mut x = 0;
|
|
|
|
|
for num in &nums {
|
|
|
|
|
x = (x + num) % p;
|
|
|
|
|
}
|
|
|
|
|
if x == 0 {
|
|
|
|
|
return 0;
|
|
|
|
|
}
|
|
|
|
|
let mut index = HashMap::new();
|
|
|
|
|
let (mut y, mut res) = (0, nums.len() as i32);
|
|
|
|
|
|
|
|
|
|
for(i, num) in nums.iter().enumerate(){
|
|
|
|
|
// println!("index is {}, value is {}", i, num);
|
|
|
|
|
index.insert(y, i as i32);
|
|
|
|
|
y = (y + num) % p;
|
|
|
|
|
if let Some(&j) = index.get(&((y - x + p) % p)){
|
|
|
|
|
res = res.min((i as i32 - j) + 1);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
// for num in &nums {
|
|
|
|
|
// println!("{}", num);
|
|
|
|
|
// }
|
|
|
|
|
if res == nums.len() as i32 {-1} else {res}
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
![image-20230310114754062](C:\Users\10074\AppData\Roaming\Typora\typora-user-images\image-20230310114754062.png)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
`iter().enumerate()` 方法来同时遍历向量和获取下标。这个方法会返回一个元组 `(usize, &T)`,其中第一个元素是下标,第二个元素是对应的元素引用。不会失去所有权。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
c++ 代码:
|
|
|
|
|
|
|
|
|
|
![image-20230310103201738](C:\Users\10074\AppData\Roaming\Typora\typora-user-images\image-20230310103201738.png)
|