LeetCode:Sort Colors - 对颜色排序(荷兰国旗问题)

1、题目名称

Sort Colors(对颜色排序)

2、题目地址

https://leetcode.com/problems/sort-colors/

3、题目内容

英文:

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.

中文:

给定一个内含n个由红色、白色和蓝色对象组成的数组,对这些对象进行排序。在本题中,红色用0表示,白色用1表示,蓝色用2表示。

4、解题方法1

虽然题目中的Hint建议你不要使用各个语言提供的Sort类函数解决本问题,但使用Arrays.sort还是可以AC本题的。

Java代码如下:

import java.util.Arrays;

/**
 * 为颜色排序
 * @文件名称 Solution.java
 * @文件作者 Tsybius2014
 * @创建时间 2016年4月16日 上午12:17:49
 */
public class Solution {
    public void sortColors(int[] nums) {
        Arrays.sort(nums);
    }
}

5、解题方法2

后来看了下讨论区,才发现这道题其实考的是“荷兰国旗问题”。

关于“荷兰国旗问题”的描述,可以参考维基百科相关页面:

https://en.wikipedia.org/wiki/Dutch_national_flag_problem

关于“荷兰国旗问题”的解决方法,这篇文章有较为详细的论述:

http://www.cnblogs.com/gnuhpc/archive/2012/12/21/2828166.html

大体思路是使用三个标记begin、curr、end,其中在遍历过程中,begin以前的对象全部是红色的,end以后的对象全部是蓝色的,迭代到最后,begin与end之间的对象一定是白色的。

解题Java代码如下:

/**
 * 为颜色排序
 * @文件名称 Solution.java
 * @文件作者 Tsybius2014
 * @创建时间 2016年4月16日 上午12:17:49
 */
public class Solution {
    public void sortColors(int[] nums) {
        int begin = 0;
        int curr = 0;
        int end = nums.length - 1;
        int temp = 0;
        while (curr <= end) {
            if (nums[curr] == 0) {
                if (begin != curr) {
                    temp = nums[begin];
                    nums[begin] = nums[curr];
                    nums[curr] = temp;
                }
                begin++;
                curr++;
            } else if (nums[curr] == 1) {
                curr++;
            } else if (nums[curr] == 2) {
                if (end != curr) {
                    temp = nums[end];
                    nums[end] = nums[curr];
                    nums[curr] = temp;
                }
                end--;
            }
        }
        
    }
}

END

转载于:https://my.oschina.net/Tsybius2014/blog/661514

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值