703042. Reorganize The Array
Easy
Reorganize The Array
Summary
The problem requires you to reorganize an array such that all elements less than a given target value appear before all elements greater than or equal to the target value. This is a classic array manipulation problem that involves sorting and rearranging the elements in a specific order.
Detailed Explanation
To solve this problem, we can use a two-pointer approach. Initialize two pointers, one at the beginning of the array (let's call it low) and one at the end of the array (let's call it high). We'll also maintain a variable target to store the target value.
Here are the steps:
- Start by initializing
lowto 0 andhighto the length of the array minus 1. - Compare the values at indices
lowandhigh. If the value at indexlowis less than the target, incrementlowand move all elements less than the target to the beginning of the array. - If the value at index
highis greater than or equal to the target, decrementhighand move all elements greater than or equal to the target to the end of the array. - Continue iterating until
lowmeetshigh. - Return the reorganized array.
Here's a step-by-step breakdown:
public static int[] reorganizeArray(int[] arr, int target) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
if (arr[low] < target && arr[high] >= target) {
break;
}
if (arr[low] < target) {
low++;
} else if (arr[high] >= target) {
high--;
} else {
int temp = arr[low];
arr[low] = arr[high];
arr[high] = temp;
low++;
high--;
}
}
return arr;
}