LeetCode 75. Sort Colors

xiaoxiao2021-02-27  169

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.

click to show follow up.


Seen this question in a real interview before? 

三种数字的排序,用三个指针做交换即可

public class Solution { public void sortColors(int[] nums) { if(nums.length<2)return ; int l = nums.length-1; int nr = 0; int nb = nums.length-1; while(nr<=l&&nums[nr]==0)nr++; while(nb>=0&&nums[nb]==2)nb--; int nw = nr; while(nw<=nb){ if(nums[nw]==1){ nw++; continue; } if(nums[nw]==0){ nums[nw] = nums[nr]; nums[nr] = 0; nr++; nw++; } else{ nums[nw] = nums[nb]; nums[nb] = 2; nb--; } } return ; } }

转载请注明原文地址: https://www.6miu.com/read-12413.html

最新回复(0)