Longest Consecutive Sequence

来源:互联网 发布:淘宝模特室内怎么布光 编辑:程序博客网 时间:2024/05/20 05:27
public class Solution {    public int longestConsecutive(int[] num) {        Set<Integer> set = new HashSet<>();        for (int i: num) {            set.add(i);        }        int longest = 0;        for (int i: num) {            if (set.contains(i)) {                int count = 1;                int low = i - 1;                while (set.contains(low)) {                    set.remove(low);                    low--;                    count++;                }                int high = i + 1;                while (set.contains(high)) {                    set.remove(high);                    high++;                    count++;                }                if (count > longest) {                    longest = count;                }            }        }        return longest;    }}

0 0
原创粉丝点击