Nums a given integer array and an integer k. Dividing the array (i.e., the mobile element in the array nums), such that:
Less than k all elements to the left
of all elements k greater than or equal to the right
to return the position of the divided array, i.e. a first position in the array i, satisfies nums [i] is greater than equal to k.
- Note
that you should really be divided nums array, rather than just counting the number of integers less than k, if all the elements in the array nums than k small, then return nums.length.
Sample
analysis array nums = [3,2,2,1] and k = 2, 1 is returned.
Challenges
using O (n) time complexity is divided on the array.
Conceptual understanding
long as l, r are moving too, l is the stop position of the first index that nums [i]> = k, like a general return l
Where r is discussed separately untouched or l, l where l untouched or return, where r untouched return r + 1
IX practice
will eventually stay in the position left = right
public class Solution{
public int partitionArray(int[] nums,int k){
if(nums==null||nums.length==0){
return -1;
}
int left=0,right=nums.length-1;//这个注意是个小的逗号
while(left<right){
while(left<right&&nums[left]<k){
left++;
}
while(left<right&&nums[right]>=k){
right--;
}
if(left<right){
int temp=nums[right];
nums[left]=nums[right];
nums[right]=temp;
left++;
right--;
}
}
if(nums[left]<k){
return left+1;//也是可以理解 这个一个没动
}
//否则
return left;
}
}
Reference other bloggers
public class Solution {
/**
*@param nums: The integer array you should partition
*@param k: As description
*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 l=0, r=nums.length-1;
while (true) {
while (l<r && nums[l]<k) {
l++;
}
while (l<r && nums[r]>=k) {
r--;
}
if (l == r) break;
swap(l, r, nums);
}
//if (l==0 && nums[l]>=k) return l;
if (r==nums.length-1 && nums[r]<k){
return r+1;
}
return l;
}
public void swap(int l, int r, int[] nums) {
int temp = nums[l];
nums[l] = nums[r];
nums[r] = temp;
}
}