码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode:Longest Consecutive Sequence

时间:2015-03-11 23:17:44      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

题目要求:

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.

题目地址:https://leetcode.com/problems/longest-consecutive-sequence/

public class Solution {
    
    public static int longestConsecutive(int[] num) {
        HashMap<Integer,Boolean> hash_array=new HashMap <Integer,Boolean>();
        for(int ele: num){
            hash_array.put(new Integer(ele), new Boolean(false));          
        }
        int max_result=0;
        for(int element:num){
            int result=0;
            
            for(int ele_x=element;(hash_array.containsKey(ele_x)) 
                    && (hash_array.get(ele_x)==false);ele_x++){
                hash_array.put(new Integer(ele_x),new Boolean(true));
                result++;
            }
            for(int ele_y=element-1;hash_array.containsKey(ele_y)
                    &&(hash_array.get(ele_y)==false);ele_y--){
                hash_array.put(new Integer(ele_y),new Boolean(true));
                result++;
            }
            max_result=result>max_result?result:max_result;
                
      
        }
        return max_result;
    }
}

数据结构题型,主要复杂度是N不能先排序在遍历最长连续子串,考虑使用hash表查找,查找复杂度就变成了1,把所有元素遍历完一遍后,即能得出最长连续子串。

leetcode:Longest Consecutive Sequence

标签:

原文地址:http://www.cnblogs.com/charlesdoit/p/4331021.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!