卖萌的弱渣

I am stupid, I am hungry.

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.

Example

If nums = [3,2,2,1] and k=2, a valid answer is 1.

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

Challenge

Can you partition the array in-place and in O(n)?

Solution

  • Time: O(N), Space O(1)
  • Scan the arrary from left to right
  • Front: index for next element which is smaller than k
  • put all elements (< k) into nums[front]
(Partition-Array.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
    """
    @param nums: The integer array you should partition
    @param k: As description
    @return: The index after partition
    """
    def partitionArray(self, nums, k):
        # write your code here
        # you should partition the nums by k
        # and return the partition index as description
        if len(nums) == 0:
            return 0
        front = 0

        for i in range(len(nums)):
            if nums[i] < k and front < len(nums):
                nums[i],nums[front] = nums[front],nums[i]
                front += 1

        for i in range(len(nums)):
            if nums[i] >= k:
                return i
        return len(nums)