leetcode: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.

题目地址: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,把所有元素遍历完一遍后,即能得出最长连续子串。

posted on 2015-03-11 21:31  Charles晟  阅读(151)  评论(0)    收藏  举报

导航