zoukankan      html  css  js  c++  java
  • leetcode 128. Longest Consecutive Sequence ----- java

    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.

    就是判断数组中最长的连续数字的长度。

    1、直接用排序。。当然不行了,时间复杂度超过了O(n),虽然AC了。

    public class Solution {
        public int longestConsecutive(int[] nums) { 
            int result = 1;
            if( nums.length == 0)
                return result;
            Arrays.sort(nums);
            for( int i = 1;i<nums.length;i++){
                int a = 1;
                while( i<nums.length && (nums[i] == nums[i-1]+1 || nums[i] == nums[i-1]) ){
                    if( nums[i] == nums[i-1]+1 )
                        a++;
                    i++;
                }
                result = Math.max(a,result);
                
            }
            return result;
            
        }
    }

    2、用set集合。遍历两次,得出结果,由于add,remove,contains都是O(1)的复杂度,所以时间复杂度符合题意。

    public class Solution {
        public int longestConsecutive(int[] nums) { 
            if( nums.length == 0)
                return 0;
            Set set = new HashSet<Integer>();
    
            for( int num : nums)
                set.add(num);
            int result = 1;
    
            for( int e : nums){
                int left = e-1;
                int right = e+1;
                int count = 1;
                while( set.contains(left )){
                    set.remove(left);
                    count++;
                    left--;
                }
                while( set.contains(right) ){
                    set.remove(right);
                    count++;
                    right++;
                }
                result = Math.max(result,count);
    
    
            }
        return result;
            
        }
    }
  • 相关阅读:
    (五)Hibernate 操作对象
    (四)关联关系一对多映射
    (三)映射对象标识符(OID)
    随机取数据
    Delphi的时间处理
    调用MYSQL存储过程实例
    php接收数据
    NodeJS入门
    idHTTP访问百度
    delphi 从TWebBrowser WebBrowser得到全部html源码
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6036152.html
Copyright © 2011-2022 走看看