feat: 2197_replace_non_coprime_numbers_in_array
This commit is contained in:
parent
90bcaf5436
commit
fc918a0a7d
7
2197_replace_non_coprime_numbers_in_array/Cargo.lock
generated
Normal file
7
2197_replace_non_coprime_numbers_in_array/Cargo.lock
generated
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
# This file is automatically @generated by Cargo.
|
||||||
|
# It is not intended for manual editing.
|
||||||
|
version = 4
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "replace_non_coprime_numbers_in_array"
|
||||||
|
version = "0.1.0"
|
6
2197_replace_non_coprime_numbers_in_array/Cargo.toml
Normal file
6
2197_replace_non_coprime_numbers_in_array/Cargo.toml
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
[package]
|
||||||
|
name = "replace_non_coprime_numbers_in_array"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
39
2197_replace_non_coprime_numbers_in_array/src/lib.rs
Normal file
39
2197_replace_non_coprime_numbers_in_array/src/lib.rs
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
pub struct Solution;
|
||||||
|
|
||||||
|
impl Solution {
|
||||||
|
pub fn replace_non_coprimes(nums: Vec<i32>) -> Vec<i32> {
|
||||||
|
let mut stack = Vec::<i32>::new();
|
||||||
|
|
||||||
|
for mut num in nums {
|
||||||
|
loop {
|
||||||
|
if stack.is_empty() {
|
||||||
|
stack.push(num);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
let top = *stack.last().unwrap();
|
||||||
|
let gcd = Solution::gcd(top, num);
|
||||||
|
if gcd == 1 {
|
||||||
|
stack.push(num);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
let lcm = top / gcd * num;
|
||||||
|
num = lcm;
|
||||||
|
stack.pop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stack
|
||||||
|
}
|
||||||
|
|
||||||
|
fn gcd(a: i32, b: i32) -> i32 {
|
||||||
|
if a == 0 {
|
||||||
|
b
|
||||||
|
} else if a <= b {
|
||||||
|
Solution::gcd(b % a, a)
|
||||||
|
} else {
|
||||||
|
Solution::gcd(b, a)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user