Leetcode049--最长连续子数组

来源:互联网 发布:apache ant windows 编辑:程序博客网 时间:2024/06/05 09:49

一、原题



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.



一、中文



给出一个数组,求出里面能够组成的最长连续子数组的长度并返回



三、举例



比如数组[100, 4, 200, 1, 3, 2]中的最长子数组的长度就是[1, 2, 3, 4]



四、思路



首先对数组进行排序,然后将排序后的数组进行查找,从最左边开始,如果相邻就加一,如果不相邻就将其置零


五、程序


import java.util.*;public class Solution {    //发现连续的子字符串    public int longestConsecutive(int[] num) {        //排序        Arrays.sort(num);                int max = 1;        int count = 1;        for(int i = 1; i < num.length; i++){            if((num[i] - num[i-1]) == 1){                count++;                if(count > max){                    max = count;                }            }else if(num[i] - num[i-1] == 0){                continue;            }else{                count = 1;            }                    }        return max;    }}