75. Sort Colors

来源:互联网 发布:公交线路查询软件 编辑:程序博客网 时间:2024/06/01 22:48

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.

Subscribe to see which companies asked this question

准备两个指针 一个指向开头的最后一个0 一个指向末尾的第一个2 然后在数组中搜索 0放前面2放后面

public class Solution {    public void sortColors(int[] nums) {        int begin = 0;        int end = nums.length-1;        int p = 0;        while(p<=end){            if(nums[p]==0){                int a = nums[begin];                nums[begin]=nums[p];                nums[p]=a;                p++;begin++;                continue;            }            if(nums[p]==2){                int a = nums[end];                nums[end]=nums[p];                nums[p]=a;                // p++;                end--;                continue;            }            p++;        }        // return nums;    }}

0 0
原创粉丝点击