给出一个整数数组 nums 和一个整数 k。划分数组(即移动数组 nums 中的元素),使得:
所有小于k的元素移到左边
所有大于等于k的元素移到右边
返回数组划分的位置,即数组中第一个位置 i,满足 nums[i] 大于等于 k。
LintCode题目地址
def partitionArray(self, nums, k):
# write your code here
n = len(nums)
if n == 0:
return 0
start, end = 0,n - 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:
tmp = nums[start]
nums[start] = nums[end]
nums[end] = tmp
start += 1
end -= 1
return start