[Leetcode]@python 75. Sort Colors
题目链接
https://leetcode.com/problems/sort-colors/
题目原文
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.
Note:
You are not suppose to use the library's sort function for this problem.
题目大意
给定n个颜色,有红、白、蓝三种颜色,分别用0,1,2三个数字表示,将这些颜色按照红白蓝的颜色排序
解题思路
记录一下起始位置和末尾。遍历一下输入,如果是2就放到末尾,末尾-1,如果是0,那么放到开始位置,其实位置+1.
代码
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
start, end = 0, len(nums) - 1
i = 0
while i <= end:
if nums[i] == 0:
nums[i], nums[start] = nums[start], nums[i]
start += 1
i += 1
elif nums[i] == 2:
nums[i], nums[end] = nums[end], nums[i]
end -= 1
else:
i += 1