LintCode-Partition Array

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.

Note

You should do really partition in array "nums" instead of just counting the numbers of integers smaller than k.

If all elements in "nums" are 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 class Solution {
 2     /**
 3      *@param nums: The integer array you should partition
 4      *@param k: As description
 5      *return: The index after partition
 6      */
 7     public int partitionArray(ArrayList<Integer> nums, int k) {
 8         //if (nums.isEmpty()) return 0;
 9         int len = nums.size();
10         if (len==0) return 0;
11 
12         int p1 = 0, p2 = len-1;
13         while (p1<len && nums.get(p1)<k) p1++;
14         while (p2>=0 && nums.get(p2)>=k) p2--;
15 
16         while (p1<p2){
17             //swap the element at p1 and p2.
18             int temp = nums.get(p1);
19             nums.set(p1,nums.get(p2));
20             nums.set(p2,temp);
21 
22             //Move p1 and p2.
23             p1++;
24             while (p1<len && nums.get(p1)<k) p1++;
25             p2--;
26             while (p2>=0 && nums.get(p2)>=k) p2--;
27         }
28 
29         return p1;
30     }
31 }

 

posted @ 2014-12-27 22:22  LiBlog  阅读(379)  评论(0编辑  收藏  举报