Skip to content

Commit b5bdde2

Browse files
committed
math
1 parent 18901d9 commit b5bdde2

File tree

1 file changed

+82
-1
lines changed

1 file changed

+82
-1
lines changed

Diff for: src/array/ext/math.rs

+82-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
//! * [1342. 将数字变成 0 的操作次数](number_of_steps)
99
//! * [836. 矩形重叠](is_rectangle_overlap)
1010
//! * [867. 转置矩阵](transpose)
11+
//! * [LCP 06. 拿硬币](min_count)
12+
//! * [2582. 递枕头](pass_the_pillow)
1113
//! * 中等
1214
//! * [462. 最小操作次数使数组元素相等 II](min_moves2)
1315
//! * [667. 优美的排列 II](construct_array)
@@ -220,7 +222,7 @@ pub fn number_of_steps(num: i32) -> i32 {
220222
/// ```
221223
/// 根据[等差数列的公式](https://en.wikipedia.org/wiki/Arithmetic_progression), 可以得到以下推导,
222224
/// 假定起始项为$a$, 差$d$为1 项数$k$, 和为$n$, 则
223-
///
225+
///
224226
/// ```math
225227
/// n = \frac{k \times (a+a+(k-1))}{2}
226228
/// ```
@@ -512,11 +514,90 @@ pub fn transpose(matrix: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
512514
return ret;
513515
}
514516

517+
/// [LCP 06. 拿硬币](https://leetcode.cn/problems/na-ying-bi)
518+
pub fn min_count(coins: Vec<i32>) -> i32 {
519+
coins.into_iter().fold(0, |acc, x| {
520+
if x % 2 == 0 {
521+
acc + x / 2
522+
} else {
523+
acc + x / 2 + 1
524+
}
525+
})
526+
}
527+
528+
/// [2582. 递枕头](https://leetcode.cn/problems/pass-the-pillow)
529+
pub fn pass_the_pillow(n: i32, time: i32) -> i32 {
530+
let step = n - 1; // 一轮步数
531+
let cycle = time / step; // 跑了几轮
532+
let remain = time % step; // 最后一轮剩余步数
533+
534+
if cycle % 2 == 0 {
535+
// 偶数轮, 从1开始
536+
1 + remain
537+
} else {
538+
// 奇数轮, 从n开始
539+
n - remain
540+
}
541+
}
542+
515543
#[cfg(test)]
516544
mod tests {
517545
use super::*;
518546
use crate::vec2;
519547

548+
#[test]
549+
fn test_pass_the_pillow() {
550+
struct TestCase {
551+
n: i32,
552+
time: i32,
553+
expect: i32,
554+
}
555+
556+
vec![
557+
TestCase {
558+
n: 3,
559+
time: 2,
560+
expect: 3,
561+
},
562+
TestCase {
563+
n: 4,
564+
time: 5,
565+
expect: 2,
566+
},
567+
]
568+
.into_iter()
569+
.enumerate()
570+
.for_each(|(idx, TestCase { n, time, expect })| {
571+
let actual = pass_the_pillow(n, time);
572+
assert_eq!(expect, actual, "case {} failed", idx);
573+
});
574+
}
575+
576+
#[test]
577+
fn test_min_count() {
578+
struct TestCase {
579+
coins: Vec<i32>,
580+
expect: i32,
581+
}
582+
583+
vec![
584+
TestCase {
585+
coins: vec![4, 2, 1],
586+
expect: 4,
587+
},
588+
TestCase {
589+
coins: vec![2, 3, 10],
590+
expect: 8,
591+
},
592+
]
593+
.into_iter()
594+
.enumerate()
595+
.for_each(|(idx, TestCase { coins, expect })| {
596+
let actual = min_count(coins);
597+
assert_eq!(expect, actual, "case {} failed", idx);
598+
});
599+
}
600+
520601
#[test]
521602
fn test_transpose() {
522603
struct TestCase {

0 commit comments

Comments
 (0)