golang 最和谐的子序列
We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.
Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.
Example 1:
Input: [1,3,2,2,5,2,3,7] Output: 5 Explanation: The longest harmonious subsequence is [3,2,2,2,3].
Note: The length of the input array will not exceed 20,000.
关于和谐子序列就是序列中数组的最大最小差值均为1。由于这里只是让我们求长度,并不需要返回具体的子序列。所以我们可以对数组进行排序,那么实际上我们只要找出来相差为1的两个数的总共出现个数就是一个和谐子序列的长度了。明白了这一点,我们就可以建立一个数字和其出现次数之间的映射,利用map的自动排序的特性,那么我们遍历map的时候就是从小往大开始遍历,我们从第二个映射对开始遍历,每次跟其前面的映射对比较,如果二者的数字刚好差1,那么就把二个数字的出现的次数相加并更新结果res即可,就是golang的实现方法,参考代码
func findLHS(nums []int) int {
//给输入的数组排序
numSlice := sort.IntSlice(nums)
sort.Sort(numSlice)
//map是无序的所以用slice来记住顺序的数字(已经去掉重复)
var keySlice []int = make([]int, 0)
var dic = make(map[int]int)
for i := 0; i < len(numSlice); i++ {
if _, ok := dic[numSlice[i]]; ok {
dic[numSlice[i]] += 1
} else {
dic[numSlice[i]] = 1
keySlice = append(keySlice, numSlice[i])
}
}
var maxLength int
for k, v := range keySlice {
if k <= len(numSlice)-1 {
if _, ok := dic[v+1]; ok {
if maxLength < dic[v]+dic[v+1] {
maxLength = dic[v] + dic[v+1]
}
}
}
}
return maxLength
}