Partition Array
Description
Given an array nums of integers and an int k, partition the array (i.e move the elements in “nums”) such that:
All elements < k are moved to the left
All elements >= k are moved to the right
Return the partitioning index, i.e the first index i nums[i] >= k.
public class Solution {
/**
* @param nums: The integer array you should partition
* @param k: An integer
* @return: The index after partition
*/
public int partitionArray(int[] nums, int k) {
// write your code here
if(nums == null || nums.length == 0){
return 0 ;
}
//int[] nums1 = new int[nums.length] ;
// for(int i = 0 ; i < nums.length -1 ;i++ ){
// nums1[i] = nums[i] ;
//}
int right = nums.length -1 ;
int left = 0 ;
while (left < right){
if(nums[left] < k ){
left++ ;
}else if (nums[right] >= k){
right-- ;
}else{
int n = nums[left] ;
nums[left] = nums[right] ;
nums[right] = n ;
}
}
for(int i = 0 ; i < nums.length ;i++ ){
if(nums[i] >= k){
return i;
}
}
return nums.length ;
}
}