75. Sort Colors
2018-03-13 本文已影响0人
Jonddy
题目要求:
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Notion:
You are not suppose to use the library's sort function for this problem.
解题思路:
- 三个指针进行移动,与目标数字进行比较,然后进行换位置。
- 示意图
class Solution(object):
def sortColors(self, nums):
"""
:param nums: List[int]
:return: void Do not return anything, modify nums in-place instead.
"""
def triPartition(nums, target):
i, j, n = 0, 0, len(nums) - 1
while j <= n:
if nums[j] > target:
nums[j], nums[n] = nums[n], nums[j]
n -= 1
elif nums[j] < target:
nums[i], nums[j] = nums[j], nums[i]
j += 1
i += 1
else:
j += 1
triPartition(nums, 1)
if __name__ == "__main__":
A = [2, 1, 1, 0, 0, 2]
Solution().sortColors(A)
print(A)