20240408 Finished
This commit is contained in:
parent
18604587bd
commit
1c8d953382
|
@ -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;
|
44
src/problem/p189_rotate_array.rs
Normal file
44
src/problem/p189_rotate_array.rs
Normal 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);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user