|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=75 lang=java |
| 3 | + * |
| 4 | + * [75] Sort Colors |
| 5 | + * |
| 6 | + * https://leetcode.com/problems/sort-colors/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Medium (43.01%) |
| 10 | + * Likes: 1899 |
| 11 | + * Dislikes: 169 |
| 12 | + * Total Accepted: 349.2K |
| 13 | + * Total Submissions: 810.9K |
| 14 | + * Testcase Example: '[2,0,2,1,1,0]' |
| 15 | + * |
| 16 | + * Given an array with n objects colored red, white or blue, sort them in-place |
| 17 | + * so that objects of the same color are adjacent, with the colors in the order |
| 18 | + * red, white and blue. |
| 19 | + * |
| 20 | + * Here, we will use the integers 0, 1, and 2 to represent the color red, |
| 21 | + * white, and blue respectively. |
| 22 | + * |
| 23 | + * Note: You are not suppose to use the library's sort function for this |
| 24 | + * problem. |
| 25 | + * |
| 26 | + * Example: |
| 27 | + * |
| 28 | + * |
| 29 | + * Input: [2,0,2,1,1,0] |
| 30 | + * Output: [0,0,1,1,2,2] |
| 31 | + * |
| 32 | + * Follow up: |
| 33 | + * |
| 34 | + * |
| 35 | + * A rather straight forward solution is a two-pass algorithm using counting |
| 36 | + * sort. |
| 37 | + * First, iterate the array counting number of 0's, 1's, and 2's, then |
| 38 | + * overwrite array with total number of 0's, then 1's and followed by 2's. |
| 39 | + * Could you come up with a one-pass algorithm using only constant space? |
| 40 | + * |
| 41 | + * |
| 42 | + */ |
| 43 | +class Solution { |
| 44 | + public void sortColors(int[] nums) { |
| 45 | + Map<Integer, Integer> map = new HashMap<>(); |
| 46 | + |
| 47 | + for (int i = 0; i < nums.length; i++) { |
| 48 | + if (map.containsKey(nums[i])) { |
| 49 | + map.put(nums[i], map.get(nums[i]) + 1); |
| 50 | + } else { |
| 51 | + map.put(nums[i], 1); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + int k = 0; |
| 56 | + for (int key = 0; key <= 2; key++) { |
| 57 | + int count = 0; |
| 58 | + if (map.containsKey(key)) { |
| 59 | + count = map.get(key); |
| 60 | + } |
| 61 | + while (count > 0) { |
| 62 | + nums[k++] = key; |
| 63 | + count--; |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | + |
0 commit comments