zoukankan      html  css  js  c++  java
  • LeetCode 75. Sort Colors

    原题链接在这里:https://leetcode.com/problems/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.

    Note:
    You are not suppose to use the library's sort function for this problem.

    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 an one-pass algorithm using only constant space?

    题解:

    Method 1 是bucket sort, 数个数,然后依次排回原数组,会扫两遍数组

    Follow up 用了Mehod 2, 是利用多个指针,指针的个数是不同元素个数-1. 例如本题中有 0 1 2三种数字,就设两个指针。

    第一个指针idx0指向最后一个0的下一位,第二个指针idx1指向最后一个1的下一位,不需要指向最后一个2的指针,它最后会指向nums 末尾.

    每当遇到0时,idx0和idx1都往后移动,每当遇到1时,idx1往后移动。

    Time Complexity: O(n), n = nums.length, one pass. Space: O(1).

    AC Java:

     1 public class Solution {
     2     public void sortColors(int[] nums) {
     3         /*
     4         //Method 1 Bucket sort
     5         if(nums == null || nums.length == 0){
     6             return;
     7         }
     8         int [] colorCount = new int[3];
     9         Arrays.fill(colorCount,0);
    10         for(int i = 0; i<nums.length; i++){
    11             colorCount[nums[i]]++;
    12         }
    13         int z = 0;
    14         for(int i = 0; i<=2; i++){
    15             while(colorCount[i]>0){
    16                 nums[z] = i;
    17                 z++;
    18                 colorCount[i]--;
    19             }
    20         }
    21         */
    22         
    23         //Method 2
    24         if(nums == null || nums.length == 0){
    25             return;
    26         }
    27         int ind0 = 0;
    28         int ind1 = 0;
    29         for(int i = 0; i<nums.length; i++){
    30             if(nums[i] == 0){
    31                 swap(nums, i, ind1);
    32                 swap(nums, ind1, ind0);
    33                 ind1++;
    34                 ind0++;
    35             }else if(nums[i] == 1){
    36                 swap(nums, i, ind1);
    37                 ind1++;
    38             }
    39         }
    40     }
    41     private void swap(int [] nums, int i, int j){
    42         int temp = nums[i];
    43         nums[i] = nums[j];
    44         nums[j] = temp;
    45     }
    46 }
  • 相关阅读:
    线程池的优雅关闭实践
    InheritableThreadLocal原理解析
    线程池踩坑
    两个线程通讯(生产-卖面包问题)
    谈谈redis的热key问题如何解决
    中国软件杯选题A1数据智能分析报告系统
    《程序员的思维修炼》读后感
    《算法导论》读后感
    《重构》读后感
    《代码整洁之道》读后感
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4851697.html
Copyright © 2011-2022 走看看