Simple Java Solution with two pointers - 48ms


  • 1
    C
    public class Solution {
        public int findLHS(int[] nums) {
            int len = nums.length;
            Arrays.sort(nums);
            int left = 0;
            int result = 0;
            for (int i = 0; i < len; i++) {
                while (left < i && (long) (nums[i] - nums[left]) > 1L) {
                    left++;
                }
                if (nums[i] == nums[left]) {
                    continue;
                }
                result = Math.max(i - left + 1, result);
            }
            return result;
        }
    }
    

Log in to reply
 

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