Leetcode Sort Colors

来源:互联网 发布:批判性思维工具 知乎 编辑:程序博客网 时间:2024/06/06 03:58

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.


Difficulty: Easy


public class Solution {    public void swap(int[] nums, int index1, int index2){        int temp = nums[index1];        nums[index1] = nums[index2];        nums[index2] = temp;        return;    }    public void sortColors(int[] nums) {        int curr = 0;        for(int i = 0; i < nums.length; i++){            if(nums[i] == 0){                swap(nums, curr, i);                curr++;            }        }        for(int i = curr; i < nums.length; i++){            if(nums[i] == 1){                swap(nums, curr, i);                curr++;            }        }    }}


0 0