Online Judge Solutions

Sunday, December 14, 2014

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)?

 
 
class Solution {
private:
    void swap(vector &A, int i, int j) {
       int t = A[i];
       A[i] = A[j];
       A[j] = t;
   }

public:
    int partitionArray(vector &nums, int k) {
        int n = nums.size();
        
        int i = 0, j = n-1;
        while(i <= j) {
            while(i <=j  && nums[i] < k) i++;
            while(i <=j  && nums[j] >= k) j--;
            
            if (i < j) swap(nums, i, j);
        }
        
        return i;
    }
};

No comments:

Post a Comment