Leetcode解题报告——128. 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.

题目大意:
给定一个无序数组,找出该数组的最大连续序列的长度

解题思路:
先将该数组排序,然后用动态规划的思路求解最大值问题
维护一个数组 dp , dp[i] 表示第i个元素与前面元素的连续长度,默认为1,表示非连续。

代码如下:

public int longestConsecutive(int[] nums) {
        if(nums.length <2) return nums.length;
            Arrays.sort(nums);
            if(nums[0] == nums[nums.length-1]) return 1;
            int [] dp = new int[nums.length];
            Arrays.fill(dp,1);
            int result = 1;
        for (int i = 1; i < nums.length; i++) {
               if(nums[i] == nums[i-1]) dp[i] = dp[i-1];
               else if (nums[i] - nums[i-1] == 1){
                   dp[i] = dp[i-1]+1;
               }
               result = Math.max(result,dp[i]);
        }
        return result;
    }

你可能感兴趣的:(Leetcode解题报告——128. Longest Consecutive Sequence)