zoukankan      html  css  js  c++  java
  • Longest Consecutive Sequence——Leetcode

    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.

    题目大意:给一个无序数组,找出最大的连续元素的长度。

    说真的,一开始这题,我想半天只想到用boolean数组mark,后来看了别人的才发现可以用set做。

    解题思路:

    把所有的数组放到set中,然后遍历数组的元素,然后分别向前、向后寻找set中是否存在,记录max。

        public int longestConsecutive(int[] nums) {
           if(nums==null||nums.length==0){
               return 0;
           }
            Set<Integer> set = new HashSet<>();
            for(int num:nums){
                set.add(num);
            }
            int max = 0;
            for(int i=0;i<nums.length;i++){
                Integer num = nums[i];
                int cnt = 1;
                while(set.contains(--num)){
                    cnt++;
                    set.remove(num);
                }
                num=nums[i];
                while(set.contains(++num)){
                    cnt++;
                    set.remove(num);
                }
                max=Math.max(max,cnt);
            }
            return max;
        }
  • 相关阅读:
    shape与reshape
    opencv4.5.0 +contrib编译流程
    人脸定位(haar特征)
    最近邻分类法
    人脸识别概述
    跟踪视频中的物体
    估算稠密光流
    resize函数
    swap函数
    hibernate的session执行增删改查方法的执行步骤
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4824386.html
Copyright © 2011-2022 走看看