Two Java Solutions: Two Point and HashMap


  • 0
    F

    //Two Point Solution:

    public int findLHS(int[] nums) {
    	if (nums == null || nums.length < 2)
    		return 0;
    
    	Arrays.sort(nums);
    	int max = Integer.MIN_VALUE;
    	int s = 0, e = 1;
    	while (e < nums.length) {
    		if (nums[e] - nums[s] == 1) {
    			max = Math.max(max, e - s + 1);
    			e++;
    		} else if (nums[e] == nums[s]) {
    			e++;
    		} else {
    			s++;
    		}
    	}
    	return max == Integer.MIN_VALUE ? 0 : max;
    }
    

    //HashMap Solution:

    public int findLHS2(int[] nums) {
    	int res = 0;
    	Map<Integer, Integer> map = new HashMap<>();
    	for (int i : nums) {
    		map.put(i, map.getOrDefault(i, 0) + 1);
    	}
    
    	for (Map.Entry<Integer, Integer> e : map.entrySet()) {
    		if (map.containsKey(e.getKey() - 1)) {
    			res = Math.max(res, e.getValue() + map.get(e.getKey() - 1));
    		}
    	}
    	return res;
    }

Log in to reply
 

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