• Sort Colors 解答


    Question

    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.

    Solution 1 -- Counting Sort

    Straight way, time complexity O(n), space cost O(1)

     1 public class Solution {
     2     public void sortColors(int[] nums) {
     3         int[] count = new int[3];
     4         int length = nums.length;
     5         for (int i = 0; i < length; i++)
     6             count[nums[i]]++;    
     7         for (int i = 0; i < count[0]; i++)
     8             nums[i] = 0;
     9         for (int i = 0; i < count[1]; i++)
    10             nums[i + count[0]] = 1;
    11         for (int i = 0; i < count[2]; i++)
    12             nums[i + count[0] + count[1]] = 2;
    13     }
    14 }

    Solution 2 -- Two Pointers

    We can use two pointers here to represent current red position and blue position. redIndex starts from 0, and blueIndex starts from length - 1.

    We traverse once from 0 to blueIndex.

    Each time we find nums[i] is not 1:

    if nums[i] is 0, we move it to redIndex position

    if nums[i] is 2, we move it to blueIndex position

    Time complexity O(n), space cost O(1) 

     1 public class Solution {
     2     public void sortColors(int[] nums) {
     3         int length = nums.length;
     4         int redIndex = 0, blueIndex = length - 1, i = 0;
     5         while (i <= blueIndex) {
     6             // If current color is red, we need to switch it to red position
     7             if (nums[i] == 0) {
     8                 // Switch nums[i] with nums[redIndex]
     9                 nums[i] = nums[redIndex];
    10                 nums[redIndex] = 0;
    11                 redIndex++;
    12                 i++;
    13             } else if (nums[i] == 2) {
    14                 // If current color is blue, we need to switch it to blue position and check switched color
    15                 // Switch nums[i] with nums[blueIndex]
    16                 nums[i] = nums[blueIndex];
    17                 nums[blueIndex] = 2;
    18                 blueIndex--;
    19             } else {
    20                 i++;
    21             }
    22         }
    23     }
    24 }
  • 相关阅读:
    关于CoreData的使用
    【转】向iOS开发者介绍C++(-)
    Storyboard里面的几种Segue区别及视图的切换:push,modal,popover,replace和custom
    【转】Object-C 多线程中锁的使用-NSLock
    写了半天的返回
    oracle 锁表问题
    LINQ的基本认识
    Oracle客户端配置
    REVERSE
    vchar2和nvchar2
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4802374.html
Copyright © 2020-2023  润新知