[lintcode]31. Partition Array

31. Partition Array

Description

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
Example 1:

Input:
[],9
Output:
0

Example 2:

Input:
[3,2,2,1],2
Output:1
Explanation:
the real array is[1,2,2,3].So return 1
Challenge
Can you partition the array in-place and in O(n)?

Notice
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

我的代码

class Solution:
    """
    @param nums: The integer array you should partition
    @param k: An integer
    @return: The index after partition
    """
    def partitionArray(self, nums, k):
        if nums == []:
            return 0
        l = len(nums)
        left = 0
        right = l-1
        while left<right and left<l-1 and right>0:
            while nums[left]<k and left<l-1:
                left += 1
            #print(left)
            while nums[right]>=k and right > 0:
                right -= 1
            #print(right)
            if left < right:
                tmp = nums[right]
                nums[right] = nums[left]
                nums[left] = tmp
                left += 1
                right -= 1
        print(nums)
        for i in range(l):
            if nums[i]>=k:
                return i
        return l

思路:

只需要把左边大于k的和右边小于k的交换就可以了。

  • 时间复杂度: O(n)
  • 出错:注意边界,一开始两个while要加上left<l-1和right>0,防止出现全部大于或者小于k的情况。
posted @ 2019-02-04 01:10  siriusli  阅读(225)  评论(0编辑  收藏  举报