Java clean code


  • 0
    M
    class Solution {
        
        class FrequencyBound{
            public int[] bounds = new int[2];
            public int frequency;
            
        }
        
        public int findShortestSubArray(int[] nums) {
            HashMap<Integer, FrequencyBound> map = new HashMap<Integer, FrequencyBound>();
            int degree = getDegree(nums, map);
            if(degree < 2){
                return degree;
            }
            
            return findShortestSubArray(nums, map, degree);
        }
        
        
        public int getDegree(int[] nums, HashMap<Integer, FrequencyBound> map){
            if(nums == null){
                return 0;
            }
            
            if(nums.length < 2){
                return nums.length;
            }
            
            int degree = 1;
            FrequencyBound fb;
            for(int i=0; i<nums.length; i++){
                if(map.containsKey(nums[i])){
                    fb = map.get(nums[i]);
                    fb.frequency++;
                    fb.bounds[1] = i;
                    map.put(nums[i], fb);
                    if(fb.frequency > degree){
                        degree = fb.frequency;
                    }
                }
                else{
                    fb = new FrequencyBound();
                    fb.frequency = 1;
                    fb.bounds[0] = i;
                    map.put(nums[i], fb);
                }
            }
            
            return degree;
        }
        
        public int findShortestSubArray(int[] nums, HashMap<Integer, FrequencyBound> map, int degree){
            if(nums == null){
                return 0;
            }
            
            if(nums.length < 2){
                return nums.length;
            }
            
            int min = nums.length, len = 1;
            FrequencyBound fb;
            for(Integer key: map.keySet()){
                fb = map.get(key);
                if(fb.frequency==degree){
                    len = fb.bounds[1] - fb.bounds[0] + 1;
                    if(len<min){
                        min = len;
                    }
                }
            }
            
            return min;
        }
    }
    

Log in to reply
 

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