Java TreeMap


  • 0
    H
        public int findLHS(int[] nums) {
            if(nums == null || nums.length == 1){   return 0;}        
            TreeMap<Integer,Integer> table = new TreeMap<Integer,Integer>();        
            for(int i=0;i<nums.length;i++){
                if(table.containsKey(nums[i]) ){
                    table.put(nums[i],table.get(nums[i])+1);
                }else{
                    table.put(nums[i],1);
                }
            }        
            Iterator<Map.Entry<Integer,Integer>> it = table.entrySet().iterator();
            boolean begin = true;	Integer first = null;
            int count = 0;	int gMax = 0;
            while(it.hasNext()){
                Map.Entry<Integer,Integer> cur = it.next();
                if(begin){
                    first = cur.getKey();
                    count = cur.getValue();
                    begin = false;
                }else{
                    if(cur.getKey() - first == 1){
                       gMax = Math.max(gMax,cur.getValue()+count);                 
                    }else{
                    	;
                    }
                    first = cur.getKey();
                    count = cur.getValue();                   
                }
            }
            return gMax;
        }
    

Log in to reply
 

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