File tree Expand file tree Collapse file tree 1 file changed +13
-17
lines changed Expand file tree Collapse file tree 1 file changed +13
-17
lines changed Original file line number Diff line number Diff line change 4242 */
4343class Solution {
4444 public void sortColors (int [] nums ) {
45- Map <Integer , Integer > map = new HashMap <>();
45+ int zero = 0 ;
46+ int second = nums .length - 1 ;
4647
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 );
48+ for (int i = zero ; i <= second ; i ++) {
49+ while (nums [i ] == 2 && i < second ) {
50+ swap (nums , i , second --);
5251 }
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 --;
52+ while (nums [i ] == 0 && i > zero ) {
53+ swap (nums , i , zero ++);
6454 }
6555 }
6656 }
57+
58+ public void swap (int [] nums , int i , int j ) {
59+ int temp = nums [i ];
60+ nums [i ] = nums [j ];
61+ nums [j ] = temp ;
62+ }
6763}
6864
You can’t perform that action at this time.
0 commit comments