数组-(partition array)数组划分为左右两个大小区间

'''
1:用一个变量right保存<k的数组长度:遇到<k的就赋值到right位置,然后right++
2:快速排序的思想
'''


class Solution:

    def partitionArray(self, nums, k):
        right = 0
        size = len(nums)
        for i in range(size):
            if nums[i] < k:
                nums[i], nums[right] = nums[right], nums[i]
                right += 1

        return right, nums


# 2 用快速排序的index选择,left=0,right=size-1
class Solution2:
    def partitionArray(self, nums, k):
        index, left, right = 0, 0, len(nums) - 1
        while left < right:
            while left < right and nums[left] < k:
                left += 1
            while right > left and nums[right] > k:
                right -= 1
            if left < right:
                nums[left], nums[right] = nums[right], nums[left]
                left += 1
                right -= 1
        return left, nums


s = Solution()
s2 = Solution2()
arr = [3, 2, 5, 6, 9, 1]
# 划分为大于4,小于4的两个部分
print('划分轴、划分结果:', s.partitionArray(arr, 4))
print('划分轴、划分结果:', s2.partitionArray(arr, 4))

划分轴、划分结果: (3, [3, 2, 1, 6, 9, 5])
划分轴、划分结果: (3, [3, 2, 1, 6, 9, 5])

posted @ 2019-03-14 22:39  jj千寻  阅读(231)  评论(0编辑  收藏  举报