lintcode_31.数组划分

给出一个整数数组 nums 和一个整数 k。划分数组(即移动数组 nums 中的元素),使得:

  • 所有小于k的元素移到左边
  • 所有大于等于k的元素移到右边

返回数组划分的位置,即数组中第一个位置 i,满足 nums[i] 大于等于 k

样例

给出数组 nums = [3,2,2,1] 和 k = 2,返回 1.

class Solution:
    """
    @param: nums: The integer array you should partition
    @param: k: An integer
    @return: The index after partition
    """
    def partitionArray(self, nums, k):
        # write your code here
        left = 0
        right = len(nums) - 1
        while left < right:
            while left < right and nums[left] < k:
                left += 1
            while left < right and nums[right] >= k:
                right -= 1
            if left<right:
                tmp = nums[left]
                nums[left] = nums[right]
                nums[right] = tmp
                left += 1
                right -= 1
            elif nums[left] < k:
                return left+1
        return left
                

九章算法:

class Solution:
    """
    @param nums: The integer array you should partition
    @param k: As description
    @return: The index after partition
    """
    def partitionArray(self, nums, k):
        start, end = 0, len(nums) - 1
        while start <= end:
            while start <= end and nums[start] < k:
                start += 1
            while start <= end and nums[end] >= k:
                end -= 1
            if start <= end:
                nums[start], nums[end] = nums[end], nums[start]
                start += 1
                end -= 1
        return start
nums[start], nums[end] = nums[end], nums[start]交换两值简单化写法
posted @ 2017-12-11 17:15  Tom_NCU  阅读(490)  评论(0编辑  收藏  举报