Skip to content

Instantly share code, notes, and snippets.

@smatthewenglish
Created November 1, 2023 17:19
Show Gist options
  • Save smatthewenglish/931daecd3e0c61953bdf126a9fbe83df to your computer and use it in GitHub Desktop.
Save smatthewenglish/931daecd3e0c61953bdf126a9fbe83df to your computer and use it in GitHub Desktop.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
Integer maxFrequency = 0;
HashMap<Integer, Integer> modeMap = new HashMap<>();
public int[] findMode(TreeNode root) {
Integer key = root.val;
Integer countKey = 1;
if(modeMap.containsKey(key)) {
countKey += modeMap.get(key) + 1;
}
if(countKey > maxFrequency) {
maxFrequency = countKey;
}
modeMap.put(key, countKey);
if(root.left != null) {
findMode(root.left);
}
if (root.right != null) {
findMode(root.right);
}
HashSet<Integer> resultSet = new HashSet<>();
modeMap.forEach((keyMap, countKeyMap) -> {
if (countKeyMap.equals(maxFrequency)) {
resultSet.add(keyMap);
}
});
int[] output = resultSet.stream().mapToInt(Integer::intValue).toArray();
return output;
}
}
@smatthewenglish
Copy link
Author

class Solution {

    Integer mode = 0;
    Integer maxFrequency = 0;

    public int minMoves2(int[] nums) {

        HashMap<Integer, Integer> modeMap = new HashMap<>();

        Integer baseCount = 1; 

        for(int i = 0; i < nums.length; i++) {

            Integer key = nums[i];
            
            if (modeMap.containsKey(key)){
                Integer keyCount = modeMap.get(key) + baseCount;
                modeMap.put(key, keyCount);
            } else {
                modeMap.put(key, baseCount);
            }
        }


        modeMap.forEach((key, value) -> {

            if(value > maxFrequency) {
                maxFrequency = value;
                mode = key; 
            }

        });

        int totalDiff = 0;
        for (int j = 0; j < nums.length; j++) {

            totalDiff += Math.abs(nums[j] - mode);
        }



        return totalDiff;    
        
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment