Longest Consecutive Sequence
Longest Consecutive Sequence
问题:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
思路:
HashSet进行存储
我的代码:
public class Solution { public int longestConsecutive(int[] num) { if(num == null || num.length == 0) return 0; Set<Integer> set = new HashSet<Integer>(); for(int i = 0; i < num.length; i++) { set.add(num[i]); } int maxLen = 0; for(int i = 0; i < num.length; i++) { if(set.contains(num[i])) { int tmp = num[i] - 1; int len = 1; set.remove(num[i]); while(set.contains(tmp)) { set.remove(tmp); len++; tmp--; } tmp = num[i] + 1; while(set.contains(tmp)) { set.remove(tmp); len++; tmp++; } maxLen = Math.max(maxLen,len); } } return maxLen; } }
学习之处:
数组映射成,用HashSet进行存储可以在O(1)快速的查找任何一个数值
posted on 2015-03-11 19:30 zhouzhou0615 阅读(119) 评论(0) 编辑 收藏 举报
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】博客园携手 AI 驱动开发工具商 Chat2DB 推出联合终身会员
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步