LeetCode 75(Sort Colors)Java

原题: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.

给定一个代表颜色的一维数组,其中用0代表红色,1代表白色,2代表蓝色。需要将相同的颜色放在一起,让他们相邻。


思路:这道题相当于对含有重复元素的数组进行排序,我代码中采用了归并排序的算法:


代码:

/*
Author:Jassy
Time:2016/11/30
Number:LeetCode 75
Resource:https://leetcode.com/problems/sort-colors/
Result:AC
Conclusion:MergeSort
*/
public class Solution {
    public void sortColors(int[] nums) {
        mergeSortColor(nums,0,nums.length-1);
    }
    
    void mergeSortColor(int[] nums,int left,int right){
        int mid=(left+right)/2;
        if(left==right){
            return;
        }else{
            mergeSortColor(nums,left,mid);
            mergeSortColor(nums,mid+1,right);
            merge(nums,left,mid,right);
        }
    }
    
    void merge(int[] nums,int left,int mid,int right){
        int[] leftSide=new int[mid-left+1];
        for(int i=left;i<=mid;i++){
            leftSide[i-left]=nums[i];
        }
        
        int[] rightSide=new int[right-mid];
        for(int i=mid;i<right;i++){
            rightSide[i-mid]=nums[i+1];
        }
        
        int leftCount=0;
        int rightCount=0;
        for(int i=left;i<=right;i++){
            if(leftCount<leftSide.length && rightCount<rightSide.length){
                if(leftSide[leftCount]<=rightSide[rightCount]){
                    nums[i]=leftSide[leftCount++];
                }else{
                    nums[i]=rightSide[rightCount++];
                }
            }else if(leftCount==leftSide.length){
                nums[i]=rightSide[rightCount++];
            }else{
                nums[i]=leftSide[leftCount++];
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值