Please judge my Solution and let me know how can I improve


  • 0
    N

    I am fairly new to coding and have no one to judge my code. I would be highly grateful if anyone can review my code and let me know on how to improve. This code works though but looking for ways to improve my skills. TIA

    private HashMap<Integer, ArrayList<Integer>> helper;
     public Solution(int[] nums) {
        helper = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int value = nums[i];
            if (helper.containsKey(value)) {
                helper.get(value).add(i);
            } else {
                ArrayList<Integer> list = new ArrayList<>();
                list.add(i);
                helper.put(value, list);
            }
        }
    }
    
    public int pick(int target) {
        if (helper.containsKey(target)) {
            if (helper.get(target).size() == 1) return helper.get(target).get(0);
            Random rn = new Random();
            return helper.get(target).get(rn.nextInt(helper.get(target).size()));
    
        } else {
            return -1;
        }
    }

Log in to reply
 

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