leetcode 75. Sort Colors

生命不息,奋斗不止


@author stormma
@date 2017/10/19


题目
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.

题目意思很简单,给你一个只包含0, 1, 2的数组然后你排序成0区,1区,2区的这种形式,这就是著名的荷兰国旗问题。

思路分析
设三个指针,初始化pos0(0区指针) = 0, pos2(2区指针) = length-1 , currentPos(当前位置指针) = 0,然后从currentPos开始判断,如果是0就和pos0这个位置的数据交换,然后pos0++, currentPos++,如果是2,那么和pos2位置交换,pos2--此时currentPos不增加(因为交换过来的上一个pos2位置的数据还没进行判断), 如果是1, currentPos++就行了,循环直到currentPos > pos2为止。

代码实现

/**
 * <p>荷兰国旗问题,<a href="https://leetcode.com/problems/sort-colors">题目链接</a></p>
 *
 * @author stormma
 * @date 2017/10/19
 */
public class Question75 {

    static class Solution {
        public void sortColors(int[] nums) {
            int pos0 = 0, pos2 = nums.length - 1, currentPos =0;
            while (currentPos <= pos2) {
                if (nums[currentPos] == 0) {
                    swap(nums, currentPos, pos0);
                    pos0++;
                    currentPos++;
                    continue;
                }
                if (nums[currentPos] == 2) {
                    swap(nums, currentPos, pos2);
                    pos2--;
                    continue;
                }
                currentPos++;
            }
            show(nums);
        }

        private static void show(int[] array) {
            for (int anArray : array) {
                System.out.print(anArray + " ");
            }
            System.out.println();
        }

        private static void swap(int[] nums, int a, int b) {
            int temp = nums[a];
            nums[a] = nums[b];
            nums[b] = temp;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值