求出Go(Golang)中最长的连续序列长度的程序

274 阅读1分钟

概述

给出一个整数数组。求其中最长的连续序列的长度。让我们看一个例子来理解它

例子1

Input: [4,7,3,8,2,1]
Output: 4
Reason: The longest consecutive sequence is [1,2,3,4]

例二

Input: [4,7,3,8,2,1,9,24,10,11]
Output: 5
Reason: The longest consecutive sequence is [7,8,9,10,11]

天真的想法是对数组进行排序并返回最长的连续序列。但是我们可以在O(n)时间内完成这个工作。我们的想法是在这里使用一个哈希值。以下是这个想法

  • 将每个数字存储在哈希中。

  • 然后从每个数字开始,找出从该数字开始的最长的连续序列的长度。因此,如果一个数字是n,我们试着在散列中找到n+1,n+2......,并得到从该数字开始的最长连续序列的长度。

  • 如果在步骤2中找到的长度大于之前找到的最长连续序列,那么就更新最长连续序列的长度

程序

以下是相同的程序

package main

import "fmt"

func longestConsecutive(nums []int) int {
	numsMap := make(map[int]int)

	lenNums := len(nums)

	for i := 0; i < lenNums; i++ {
		numsMap[nums[i]] = 0
	}

	maxLCS := 0
	for i := 0; i < lenNums; i++ {
		currentLen := 1
		counter := 1

		for {
			val, ok := numsMap[nums[i]+counter]
			if ok {
				if val != 0 {
					currentLen += val
					break
				} else {
					currentLen += 1
					counter += 1
				}
			} else {
				break
			}
		}

		if currentLen > maxLCS {
			maxLCS = currentLen
		}
		numsMap[nums[i]] = currentLen
	}

	return maxLCS
}

func main() {
	output := longestConsecutive([]int{4, 7, 3, 8, 2, 1})
	fmt.Println(output)

	output = longestConsecutive([]int{4, 7, 3, 8, 2, 1, 9, 24, 10, 11})
	fmt.Println(output)

}

输出:

4
5