20240408 Finished

This commit is contained in:
jackfiled 2024-04-08 11:02:39 +08:00
parent 18604587bd
commit 1c8d953382
2 changed files with 46 additions and 1 deletions

View File

@ -95,4 +95,5 @@ mod p88_merge_sorted_array;
mod p26_remove_duplicates_from_sorted_array;
mod p27_remove_element;
mod p80_remove_duplicates_from_sorted_array_ii;
mod p169_majority_element;
mod p169_majority_element;
mod p189_rotate_array;

View File

@ -0,0 +1,44 @@
/**
* [189] Rotate Array
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn rotate(nums: &mut Vec<i32>, k: i32) {
let k = (k as usize) % nums.len();
if k == 0 {
return;
}
let mut temp = Vec::with_capacity(k);
for i in (nums.len() - k)..nums.len() {
temp.push(nums[i]);
}
for i in (0..(nums.len() - k)).rev() {
nums[i + k] = nums[i];
}
for i in 0..k {
nums[i] = temp[i];
}
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_189() {
let mut array = vec![1, 2, 3, 4, 5, 6, 7];
Solution::rotate(&mut array, 3);
assert_eq!(vec![5, 6, 7, 1, 2, 3, 4], array);
}
}