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 is moved to the left
* All elements >= K is moved to the right
Return the partitioning index, i.e the first index "I" nums[i] >= K.
Note
You should does really partition in array "Nums" instead of just counting the numbers of integers smaller than K.
If all elements in "nums" is smaller than K, then return "Nums.length"
Example
If nums=[3,2,2,1] and k=2, a valid answer is 1.
Challenge
Can you partition the array in-place and in O (n)?
Solution:
1 Public classSolution {2 /**3 *@paramnums:the integer array you should partition4 *@paramK:as Description5 *return:the Index after partition6 */7 Public intPartitionarray (arraylist<integer> nums,intk) {8 //if (Nums.isempty ()) return 0;9 intLen =nums.size ();Ten if(len==0)return0; One A intP1 = 0, p2 = len-1; - while(P1<len && Nums.get (p1) <k) p1++; - while(P2>=0 && nums.get (p2) >=k) p2--; the - while(p1<p2) { - //swap the element at P1 and P2. - inttemp =Nums.get (p1); + Nums.set (P1,nums.get (p2)); - Nums.set (p2,temp); + A //Move p1 and P2. atp1++; - while(P1<len && Nums.get (p1) <k) p1++; -p2--; - while(P2>=0 && nums.get (p2) >=k) p2--; - } - in returnP1; - } to}
Lintcode-partition Array