LeetCode 75. Sort Colors 题解

末蓝、 2021-11-22 09:36 283阅读 0赞

Difficulty: Medium

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.

click to show follow up.

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?

  1. public class Solution {
  2. public void sortColors(int[] nums) {
  3. //method 1 two-pass algorithm
  4. /**int r = 0, w = 0, b = 0;
  5. int length = nums.length;
  6. if (length == 1){
  7. return;
  8. }
  9. int i = 0;
  10. for ( i=0; i<length; i++){
  11. switch(nums[i]){
  12. case 0:
  13. r++;
  14. break;
  15. case 1:
  16. w++;
  17. break;
  18. case 2:
  19. b++;
  20. break;
  21. }
  22. }
  23. for (i=0; i<r; i++){
  24. nums[i] = 0;
  25. }
  26. for (i=0; i<w; i++){
  27. nums[r+i] = 1;
  28. }
  29. for (i=0; i<b; i++){
  30. nums[r+w+i] = 2;
  31. }**/
  32. //method 2 one-pass algorithm
  33. int length = nums.length;
  34. int red = 0, blue = length - 1;
  35. int i=0;
  36. while(i < length){
  37. if (nums[i] == 0){
  38. int tempR = nums[i];
  39. nums[i] = nums[red];
  40. nums[red] = tempR;
  41. red++;
  42. i++;
  43. continue;
  44. }
  45. if(nums[i] == 2 && i<blue){
  46. int tempB = nums[blue];
  47. nums[blue] = nums[i];
  48. nums[i] = tempB;
  49. blue--;
  50. continue;
  51. }
  52. i++;
  53. }
  54. }
  55. }

转载于:https://www.cnblogs.com/liveandlearn/p/5601462.html

发表评论

表情:
评论列表 (有 0 条评论,283人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LeetCode75——Sort Colors

    LeetCode75——Sort Colors 简要的分析一下题意就是对只包含 0,1,2 这三个数的数组进行排序。 这里提供三种方案,前两种是自己Y出来的,后一种是大