Leetcode 75 Sort Colors

参考资料:左程云算法课

75. Sort Colors
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

You must solve this problem without using the library's sort function.

 

Example 1:

Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

思路:荷兰国旗问题,快速排序的partition函数。
把数组分为<1Area, =1Area, >1Area等三个区;
<1Area 的右边界(闭的)用less表示,
>1Area 的左边界(闭的)用more表示,
cur是用于遍历数组的指针,
如果他所指的元素大于1,那么 把当前元素发货到>1Area 的最新左边界位置(相当于向左扩展左边界), and cur++;
如果他所指的元素小于1,那么 把当前元素发货到<1Area` 的最新右边界位置(相当于向右扩展右边界), and cur++;
如果他所指的元素等于1,那么 把他留在这,that is =Area, and cur++,

class Solution {
    public void sortColors(int[] nums) {

        int n = nums.length;
        // <1 =1, >1

        int less=-1;
        int more = n;
        int cur=0;
    // nums[cur], <1 less++,cur++, ==1 cur++, >1 swap(nums,cur,--more)
        while(cur<more)
        {
            if(nums[cur]<1)
            {
                swap(nums,cur++,++less);

            }else if(nums[cur]==1)
            {
                //swap(nums,cur++,1+less);
                cur++;
            }else{
                swap(nums,cur,--more);
            }
        }// end while


    }

    public void swap(int[] nums, int i, int j)
    {
        int t= nums[i];
        nums[i] = nums[j];
        nums[j]=t;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值