当前位置:   article > 正文

Sort Colors_sorting colored array

sorting colored array

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?


Analyze:

We use two pointers to point to the places where 0 and 2 should be inserted. We use another pointer to enumerate all the values in the array.

Code:

  1. public class Solution {
  2. public void sortColors(int[] A) {
  3. if (A == null || A.length == 0) return;
  4. int left = 0;
  5. int right = A.length - 1;
  6. int cur = left;
  7. while(cur <= right) {
  8. if (A[cur] == 0) {
  9. swap(A, left++, cur);
  10. cur = (cur <= left) ? left : cur;
  11. } else if (A[cur] == 2) {
  12. swap(A, right--, cur);
  13. } else {
  14. cur++;
  15. }
  16. }
  17. }
  18. public void swap(int[] A, int i, int j) {
  19. int temp = A[i];
  20. A[i] = A[j];
  21. A[j] = temp;
  22. }
  23. }



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/75104
推荐阅读
相关标签
  

闽ICP备14008679号