LeetCode-75-Sort Colors

算法描述:

Given an array with n objects colored red, white or blue, sort them in-place 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.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Follow up:

  • A rather straight forward solution is a two-pass algorithm using counting sort.
    First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
  • Could you come up with a one-pass algorithm using only constant space?
Accepted

解题思路:三种颜色,用三个指针区分。用中间的指针进行扫描,每次扫描完进行交换。如果值等于0,left和index指针进行交换,并且两个指针都右移动。如果值等于1,则只移动中间指针继续扫描。如果值等于2,将index和right进行交换,并右指针左移,index保持不变。因为index和right交换后,index所指的值是未知的,需要重新判断一下。

    void sortColors(vector<int>& nums) {
        if(nums.size() ==0) return;
        int left = 0;
        int right = nums.size()-1;
        int index = 0;
        while(index <= right){
            if(nums[index]==0){
                swap(nums, left, index);
                left++;
                index++;
            } else if (nums[index]==1){
                index++;
            } else{
                swap(nums,index,right);
                right--;
            }
        }
    }
    
    void swap(vector<int>& nums, int da, int db){
        int temp = nums[da];
        nums[da] = nums[db];
        nums[db] = temp;
    }

猜你喜欢

转载自www.cnblogs.com/nobodywang/p/10344760.html