Leetcode: Sort Colors

来源:互联网 发布:手机淘宝店招尺寸像素 编辑:程序博客网 时间:2024/06/11 11:23

Question

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.

click to show follow up.

Hide Tags Array Two Pointers Sort


Analysis

In this problem, we don′t need to know the order of all 0, 1, and 2. It requires us to modify nums in-place. we need to know the end of nums, the end of 0s. In this case, when if we encounter 0, we put it at the begining of nums; if encounter 1, we put it after redp; if encounter 2, we do nothing.


My Solution

class Solution:    # @param {integer[]} nums    # @return {void} Do not return anything, modify nums in-place instead.    def sortColors(self, nums):        redp = -1;        end = -1;        while(end<len(nums)-1 and len(nums)>0):            if nums[end+1]==0:                del nums[end+1]                nums.insert(0,0)                redp = redp + 1            elif nums[end+1]==1:                del nums[end+1]                nums.insert(redp+1, 1)            end = end + 1


0 0
原创粉丝点击