思路
数组划分
快排的一个Step
方法一:两个指针head & tail, 交替比较直到head 和 tail 重合
方法二:直接求比他小的数字的个数
Python
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
nums = [k] + nums
head, tail = 0, len(nums) - 1
target = 0
flag = False
while head <= tail:
if not flag:
if nums[target] > nums[tail]:
nums[target], nums[tail] = nums[tail], nums[target]
target = tail
flag = not flag
else:
tail -= 1
if flag:
if nums[target] <= nums[head]:
nums[target], nums[head] = nums[head], nums[target]
target = head
flag = not flag
else:
head += 1
return target
def partitionArray2(self, nums, k):
index = 0
for num in nums:
if num < k:
index += 1
return index
if __name__ == "__main__":
s = Solution()
print(s.partitionArray2([3, 2, 2, 1], 2))
print(s.partitionArray2([1, 2, 3, 4], 5))
print(s.partitionArray2([2, 1, 3, 4, 2, 2], 2))
print(s.partitionArray2([9, 9, 9, 8, 9, 8, 7, 9, 8, 8, 8, 9, 8, 9, 8, 8, 6, 9], 9))