码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Sort Colors

时间:2015-05-13 13:00:34      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:leetcode

     题意:

     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.


     思路:

     就是要你自己写个排序。下面用了快排,已优化。


     代码:

     C++:

class Solution {
public:
    void sortColors(int A[], int n) {
        quickSort(A,0,n-1);
    }

    void quickSort(int num[], int l, int r)
    {
        if(l >= r) return;

        int k = l + rand()%(r-l+1);
        int t = num[k];
        num[k] = num[l];
        num[l] = t;

        if(r - l + 1 < 8){
            for(int i = l+1;i <= r;++i)
                if(num[i] < num[i-1])
                {
                    int j,t = num[i];
                    for(j = i-1;j >= 0 && num[j] > t;j--)
                        num[j+1] = num[j];
                    num[j+1] = t;
                }
            return;
        }

        int i = l,j = r,key = num[l];
        while(i < j)
        {
            while(i < j && num[j] > key)
                j--;
            if(i < j) num[i++] = num[j];

            while(i < j && num[i] < key)
                i++;
            if(i < j) num[j--] = num[i];
        }
        num[i] = key;

        quickSort(num,l,i-1);
        quickSort(num,i+1,r);
    }
};

     Python:

import random
class Solution:
    # @param {integer[]} nums
    # @return {void} Do not return anything, modify nums in-place instead.
    def sortColors(self, nums):
        self.quickSort(nums,0,len(nums)-1)
        
    def quickSort(self,nums,l,r):
        if l >= r:
            return
        
        k = l + random.randint(0,r-l)
        t = nums[l]
        nums[l] = nums[k]
        nums[k] = t
        
        i = l
        j = r
        key = nums[l]
        while i < j:
            while i < j and nums[j] > key:
                j = j-1
            if i < j:
                nums[i] = nums[j]
                i = i+1
            
            while i < j and nums[i] < key:
                i = i+1
            if i < j:
                nums[j] = nums[i]
                j = j-1
        nums[i] = key
        
        self.quickSort(nums,l,i-1)
        self.quickSort(nums,i,r)

【LeetCode】Sort Colors

标签:leetcode

原文地址:http://blog.csdn.net/jcjc918/article/details/44513949

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!