Java hashmap time O(n) space O(1)


  • 0
    A
    import java.util.*;
    
    public class Solution {
        public void sortColors(int[] nums) {
            HashMap<Integer, Integer> hashmap = new HashMap<Integer, Integer>();
            int i,j,idx;
            for (i = 0; i < nums.length; i++) {
                if (hashmap.get(nums[i]) == null) {
                    hashmap.put(nums[i], 1);
                }
                else{
                    hashmap.put(nums[i], hashmap.get(nums[i]) + 1);
                }
            }
            for (j = 0, idx = 0; j <= 2; j++) {
                for (i = 0; hashmap.get(j) != null && i < hashmap.get(j); i++, idx++) {
                    nums[idx] = j;
                }
            }
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.