LeetCode Longest Consecutive Sequence
2015-10-18 08:03
786 查看
原题链接在这里:https://leetcode.com/problems/longest-consecutive-sequence/
题目:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given
The longest consecutive elements sequence is
Your algorithm should run in O(n) complexity.
题解:
用HashSet把所有点放入hs中,从nums[0]开始检查是否包含这个点,若是包含,就看它往下能走多远,然后看往上能走多远,走过的点从hs中移除,维护最大值。
Time Complexity O(n), Space O(n).
AC Java:
类似Binary Tree Longest Consecutive Sequence.
题目:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given
[100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is
[1, 2, 3, 4]. Return its length:
4.
Your algorithm should run in O(n) complexity.
题解:
用HashSet把所有点放入hs中,从nums[0]开始检查是否包含这个点,若是包含,就看它往下能走多远,然后看往上能走多远,走过的点从hs中移除,维护最大值。
Time Complexity O(n), Space O(n).
AC Java:
public class Solution { public int longestConsecutive(int[] nums) { if(nums == null || nums.length == 0){ return 0; } HashSet<Integer> hs = new HashSet<Integer>(); //put every element into hashset for(int i = 0; i<nums.length; i++){ hs.add(nums[i]); } int res = 0; for(int i = 0; i<nums.length; i++){ if(hs.contains(nums[i])){ int count = 1; //check how many nodes are there in lower branch int low = nums[i] - 1; while(hs.contains(low)){ hs.remove(low); low--; count++; } //check how many nodes are there in higher branch int high = nums[i] + 1; while(hs.contains(high)){ hs.remove(high); high++; count++; } res = Math.max(res,count); } } return res; } }
类似Binary Tree Longest Consecutive Sequence.
相关文章推荐
- easyui-layout个人实例
- easyui-combotree个人实例
- easyui-combotree个人实例
- N-Queens II 解答
- N-Queens 解答
- StringBuffer与StringBuilder原理与区别
- Hibernate中单向一对多,单向多对一,双向一对多 inverse="true" casecade="save-update"的理解
- Mod 与 RequireJS/SeaJS 的那些事
- Permutation Sequence 解答
- android多分辨率多屏幕密度下UI适配方案
- 2015 NEERC F. Gourmet and Banquet
- 控制器管理UINavigationController、UINavigationBar
- UIScrollView
- 物理引擎UIDynamic
- 呈现样式UIModalPresentation
- Hibernate的命名查询(NamedQuery)
- 百度编辑器ueditor的简单使用
- QuickFix/N简介
- QuickFIX/N入门:(三)如何配置QuickFIX/N
- InvokeRequired和Invoke