本文主要是介绍[LeetCode] 128. Longest Consecutive Sequence,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题:https://leetcode.com/problems/longest-consecutive-sequence/description/
题目
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
#思路
两种方式
##1.
利用sort先对nums进行排序,然后遍历一次,如果当前遍历的和上次访问的数据相同则跳过,否则,若当前数据比上次访问的数据大一,则不同。
##2.
利用 set对nums进行set操作。
##Solution
https://leetcode.com/problems/longest-consecutive-sequence/solution/
#code
1.
class Solution:def longestConsecutive(self, nums):""":type nums: List[int]:rtype: int"""if len(nums) == 0:return 0nums.sort()longest_streak = 1current_streak = 1for i in range(1,len(nums)):if nums[i]!=nums[i-1]:if nums[i] == nums[i-1]+1:current_streak +=1else:longest_streak = max(longest_streak,current_streak)current_streak =1return max(longest_streak,current_streak)
class Solution:def longestConsecutive(self, nums):""":type nums: List[int]:rtype: int"""longest_streak = 0numsset = set(nums)for num in nums:if num-1 not in numsset:current_num = numcurrent_streak = 1while current_num + 1 in numsset:current_num +=1current_streak +=1longest_streak = max(longest_streak,current_streak)return longest_streak
第二版
- 将 nums中元素放入 set中。
- 遍历set中元素,若 该元素+1的数 在set中,那么不断遍历递增元素,求出最长序列;若 元素-1的数 在 set中,那么就不求最长序列。因为当遍历到 该元素-1 的数时,统计最长序列会包含以该元素为起点的最长序列。
class Solution {public int longestConsecutive(int[] nums) {Set<Integer> set = new HashSet<>();for(int num:nums)set.add(num);int max = 0;for(int num : nums){if(set.contains(num -1))continue;int start =num;while(set.contains(num+1)){num++;}max = Math.max(max,num - start +1);}return max;}
}
这篇关于[LeetCode] 128. Longest Consecutive Sequence的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!