Simple java iteration solution


  • 0
    V
    public int findLHS(int[] nums) {
            if (nums.length < 2) {
                return 0;
            }
            Arrays.sort(nums);
            int i = 0;
            int j = 0;
            int k = 0;
            int longest = 0;
            while (j < nums.length) {
                if (nums[j] - nums[i] == 0) {
                    j += 1;
                } else if (nums[j] - nums[i] == 1) {
                    if (j == nums.length - 1) {
                        int l = j - i + 1;
                        if (l > longest) {
                            longest = l;
                        }
                    }
                    if (nums[j - 1] == nums[i]) {
                        k = j;
                    }
                    j += 1;
                } else {
                    if (nums[k] == nums[i] + 1) {
                        int l = j - i;
                        if (l > longest) {
                            longest = l;
                        }
                    }
                    if (nums[j] == nums[k] + 1) {
                        i = k;
                        k = j;
                    } else {
                        i = j;
                    }
                }
            }
            return longest;
        }
    

Log in to reply
 

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