...

/

Solution Review: Rearrange Sorted Array in Max/Min Form

Solution Review: Rearrange Sorted Array in Max/Min Form

This review provides a detailed analysis to help solve the "Rearrange Sorted Array in Max/Min Form" challenge.

Solution 1: Creating a new array

Press + to interact
fn max_min(arr: &Vec<i32>) -> Vec<i32>{
// Create a result array to hold re arranged versions
let mut result: Vec<i32> = vec![0; arr.len()];
let mut pointer_small = 0;
let mut pointer_large = arr.len() - 1;
let mut switch_pointer: bool = true;
for i in 0..arr.len(){
if switch_pointer {
result[i] = arr[pointer_large];
pointer_large -= 1;
}
else{
result[i] = arr[pointer_small];
pointer_small += 1;
}
switch_pointer = !switch_pointer;
}
result
}

Explanation

In this solution, first create an empty array result whose size is equal to the size of the original array arr. Then start iterating over the array. Store the maximum number in the start of the array, then store the minimum number next to it, and so on. In the end, you should store the result array to the original array. Look at the example below:

Time complexity

The time complexity of this problem is O(n) ...

Access this course and 1400+ top-rated courses and projects.