LeetCode Sort Colors(Dutch National Flag problem )(java & golang)

Problem
在这里插入图片描述
Analysis Process
The question is known as the Dutch National Flag problem
We use three Pointers (p0, p2, and curr) to track the right-most boundary of 0, the left-most boundary of 2, and the currently considered element, respectively
The idea of this solution is to move the curr pointer along the array, if nums[curr] = 0, then it is interchanged with nums [p0]; If nums [curr] = 2, it is interchanged with nums [p2]

Code
golang

func sortColors(nums []int)  {
    if len(nums)==0{
        return
    }
    // Initializes three Pointers
    p0:=0
    p2:=len(nums)-1
    curr:=0
    // curr  traverse
    for curr<=p2{
        if nums[curr]==0{ // Swap the p0 and curr elements
            nums[curr]=nums[p0]
            nums[p0]=0
            p0++
        }else if nums[curr]==1{
            curr++
        }else if nums[curr]==2{ //Swap the k and curr elements
            nums[curr]=nums[p2]
            nums[p2]=2
            p2--
        }
        if curr<p0{      
            curr=p0
        }
    }
}

java

class Solution {
  public void sortColors(int[] nums) {
    // for all idx < i : nums[idx < i] = 0
    // j is the subscript of the element under consideration
    int p0 = 0, curr = 0;
    // for all idx > k : nums[idx > k] = 2
    int p2 = nums.length - 1;

    int tmp;
    while (curr <= p2) {
      if (nums[curr] == 0) {
        // Swap the p0 and curr elements
        // i++,j++
        tmp = nums[p0];
        nums[p0++] = nums[curr];
        nums[curr++] = tmp;
      }
      else if (nums[curr] == 2) {
        // Swap the k and curr elements
        // p2--
        tmp = nums[curr];
        nums[curr] = nums[p2];
        nums[p2--] = tmp;
      }
      else curr++;
    }
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值