1. 程式人生 > >golang 最和諧的子序列

golang 最和諧的子序列

數組排序 pos max dia keys exactly iou 需要 logs

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
}

  

golang 最和諧的子序列