zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    vue+axios实现文件下载
    处理 Vue 单页面应用 SEO
    JSON.parse()与JSON.stringify()的区别
    JS设置Cookie过期时间
    <div>标签仿<textarea>。contentEditable=‘true’,赋予非表单标签内容可以编辑
    CSS上下左右居中的几种方法
    jqGrid 修改单元格值或者替换图片及其他
    对于Web性能优化, 了解和经验
    初步了解反射案列
    JS IndexOf移除符合规则的一项
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4802374.html
Copyright © 2011-2022 走看看