594.最长和谐子序列

122 阅读1分钟

题目:
和谐数组是指一个数组里元素的最大值和最小值之间的差别 正好是 1 。

现在,给你一个整数数组 nums ,请你在所有可能的子序列中找到最长的和谐子序列的长度。

数组的子序列是一个由数组派生出来的序列,它可以通过删除一些元素或不删除元素、且不改变其余元素的顺序而得到。
解法:
方法一:hash table 我们用hash table存储每个数组出现的次数,然后遍历hash table,找到当前数的出现次数和比当前数少一的数的出现次数,两者相加即是结果。

func findLHS(nums []int) int {
	numCount := make(map[int]int)
	for i := range nums {
		if _, ok := numCount[nums[i]]; ok {
			numCount[nums[i]] ++
		} else {
			numCount[nums[i]] = 1
		}
	}
	ans := 0
	for num, count := range numCount {
		max := numCount[num - 1]
		if numCount[num + 1] > max {
			max = numCount[num + 1]
		}
		if max != 0 && count + max > ans {
			ans = count + max
		}
	}
	return ans
}

方法二:排序+滑动窗口
对nums升序排序,找到相邻两个数差小于1,并且窗口左侧数字和右侧数字不相等的最大长度

func findLHS(nums []int) int {
    sort.Ints(nums)
    ans := 0
    
    for left, right := 0, 0; right < len(nums); left ++ {
        for right < len(nums) && nums[right] - nums[left] <= 1 {
            right ++
        }
        if right - left > ans && nums[left] != nums[right - 1] {
            ans = right - left
        }
    }
    return ans