75. 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.

思路:我们用两个指针,一个指向头,一个指向尾。 大概思路就是把0元素放到left左边,2放到right右边。用一个pointer指针从左往右开始遍历,当遇到0时,0与left位置上的元素交换, 当遇到2的时候,与right进行交换,注意:right位置的元素可能为0,right把0元素交换到前面的时候,需要下次再判断一次,看是否需要跟left交换。
复杂度: time O(n), space: O(1)

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

        }

    }

    public void swap(int[] nums, int n1, int n2) {
        int tmp = nums[n1];
        nums[n1] = nums[n2];
        nums[n2] = tmp;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s