use HashMap


  • 0
    M

    public class Solution {

    public List<String> readBinaryWatch(int num) {
        List<String> result = new ArrayList<>();
        if (num == 0) {
            result.add("0:00");
            return result;
        } 
        if (num > 8) {
            return result;
        }
        //store all the numbers and counts of digit 1
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 0; i <= 59; i++) {
            helper(i, map);
        }
       
        
        for (int i = 0; i <= num && i <= 3; i++) {
            int j = num - i;
            if (j <= num && j <= 5) {
                //num of 1 digits of minute
                
                List<Integer> h = map.get(i);
                List<Integer> m = map.get(j);
            
                for (int hour : h) {
                    if (hour <= 11) {
                        for (int min : m) {
                            String cur = hour + ":";
                            if (min < 10) {
                                cur += "0" + min;
                            } else {
                                cur += min + "";
                            }
                            result.add(cur);
                        }   
                    }
                }
                
            }
        }
        return result;
    }
    public void helper (int num, Map<Integer, List<Integer>> map) {
        int count = 0;
        int temp = num;
        while (temp != 0) {
            if ((temp & 1) == 1) {
                count++;
            }
            temp >>= 1;
        }
        List<Integer> list;
        if (!map.containsKey(count)) {
            list = new ArrayList<>();
            list.add(num);
            map.put(count, list);
            return;
        }
        list = map.get(count);
        list.add(num);
        map.put(count, list);
    }            
    

    }


Log in to reply
 

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