LeetCode(75):Sort Colors

本文介绍了一个特定场景下的数组排序问题,即数组中仅包含0、1、2三个元素,并且不使用排序库函数。通过使用双指针技巧,实现将相同颜色的元素排列在一起,且顺序为0、1、2。详细解释了算法思路及代码实现。

Sort Colors: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元素的数组进行排序,不能调用排序的库函数。

思路:由于数组中只包含3个元素,排序的结果为0在数组的左部,1在中部,2在右部。所以可以可以使用双指针分别一个left和一个right分别指向数组的首元素和末尾元素。然后开始遍历,如果遇到0就和left所指的元素交换,left指针加1,如果遇到2就和right所指的元素交换,right指针减1,遇到1就跳过,直到和right相遇。

代码:

public void sortColors(int[] nums) {
       int temp=0;
       int left = 0,right=nums.length-1;
       int i=0;
       while(i<=right){
           if(nums[i]==0){
               temp = nums[i];
               nums[i] =nums[left];
               nums[left] = temp;
               left++;
               i++;
           }else if(nums[i]==2){
               temp = nums[i];
               nums[i] =nums[right];
               nums[right] = temp;
               right--;
           }else {
               i++;
           }
       }
    }

转载于:https://www.cnblogs.com/Lewisr/p/5161434.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值