美文网首页LeetCode By Go
[LeetCode By Go 65]594. Longest

[LeetCode By Go 65]594. Longest

作者: miltonsun | 来源:发表于2017-08-29 11:34 被阅读7次

题目

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 numMap中,遍历map,统计临近数字出现次数和的最大值

代码

func findLHS(nums []int) int {
    var numMap map[int]int
    numMap = make(map[int]int)
    
    for _, v := range nums {
        numMap[v]++
    }
    
    var LHS int
    for k, v := range numMap {
        tmp1, ok1 := numMap[k-1]
        if ok1 && tmp1 + v > LHS {
            LHS = tmp1 + v
        }
        
        tmp2, ok2 := numMap[k+1]
        if ok2 && tmp2 + v > LHS {
            LHS = tmp2 + v
        }
    }
    
    return LHS
}

相关文章

网友评论

    本文标题:[LeetCode By Go 65]594. Longest

    本文链接:https://www.haomeiwen.com/subject/molodxtx.html