Java 2 pointer solution, fast, minimum calc


  • 0
    H
        public int findLHS(int[] nums) {
            Arrays.sort(nums);
            int first = 0, second = -1;
            int longest = 0;
            int i = 1;
            while(i < nums.length) {
                if (nums[i] - nums[i - 1] > 1) {
                    if (second != -1)
                        longest = Math.max(i - first, longest);
                    first = i;
                    second = -1;
                } else if (nums[i] - nums[i - 1] == 1) {
                    if(second != -1) {  //e.g. 11122333, when i on the first 3.
                        longest = Math.max(i - first, longest);
                        first = second;
                    }
                    second = i;
                }
                i++;
            }
            if(second != -1)
                longest = Math.max(i-first, longest);
            return longest;
        }
    

Log in to reply
 

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