[LeetCode] 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.

Your algorithm should run in O(n) complexity.

 

这道题要求求最长连续序列,并给定了O(n)复杂度限制,我们的思路是,使用一个集合set存入所有的数字,然后遍历数组中的每个数字,如果其在集合中存在,那么将其移除,然后分别用两个变量pre和next算出其前一个数跟后一个数,然后在集合中循环查找,如果pre在集合中,那么将pre移除集合,然后pre再自减1,直至pre不在集合之中,对next采用同样的方法,那么next-pre-1就是当前数字的最长连续序列,更新res即可。代码如下:

 

C++ 解法一:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        int res = 0;
        unordered_set<int> s(nums.begin(), nums.end());
        for (int val : nums) {
            if (!s.count(val)) continue;
            s.erase(val);
            int pre = val - 1, next = val + 1;
            while (s.count(pre)) s.erase(pre--);
            while (s.count(next)) s.erase(next++);
            res = max(res, next - pre - 1);
        }
        return res;
    }
};

 

Java 解法一:

public class Solution {
    public int longestConsecutive(int[] nums) {
        int res = 0;
        Set<Integer> s = new HashSet<Integer>();
        for (int num : nums) s.add(num);
        for (int num : nums) {
            if (s.remove(num)) {
                int pre = num - 1, next = num + 1;
                while (s.remove(pre)) --pre;
                while (s.remove(next)) ++next;
                res = Math.max(res, next - pre - 1);
            }
        }
        return res;
    }
}

 

我们也可以采用哈希表来做,刚开始哈希表为空,然后遍历所有数字,如果该数字不在哈希表中,那么我们分别看其左右两个数字是否在哈希表中,如果在,则返回其哈希表中映射值,若不在,则返回0,然后我们将left+right+1作为当前数字的映射,并更新res结果,然后更新d-left和d-right的映射值,参见代码如下:

 

C++ 解法二:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        int res = 0;
        unordered_map<int, int> m;
        for (int d : nums) {
            if (!m.count(d)) {
                int left = m.count(d - 1) ? m[d - 1] : 0;
                int right = m.count(d + 1) ? m[d + 1] : 0;
                int sum = left + right + 1;
                m[d] = sum;
                res = max(res, sum);
                m[d - left] = sum;
                m[d + right] = sum;
            }
        }
        return res;
    }
};

 

Java 解法二:

public class Solution {
    public int longestConsecutive(int[] nums) {
        int res = 0;
        Map<Integer, Integer> m = new HashMap<Integer, Integer>();
        for (int num : nums) {
            if (m.containsKey(num)) continue;
            int left = m.containsKey(num - 1) ? m.get(num - 1) : 0;
            int right = m.containsKey(num + 1) ? m.get(num + 1) : 0;
            int sum = left + right + 1;
            m.put(num, sum);
            res = Math.max(res, sum);
            m.put(num - left, sum);
            m.put(num + right, sum);
        }
        return res;
    }
}

 

类似题目:

Binary Tree Longest Consecutive Sequence

 

参考资料:

https://discuss.leetcode.com/topic/6148/my-really-simple-java-o-n-solution-accepted

https://discuss.leetcode.com/topic/16483/a-simple-c-solution-using-unordered_set-and-simple-consideration-about-this-problem

 

LeetCode All in One 题目讲解汇总(持续更新中...)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
LeetCode(力扣)上,有一个经典的算法题目叫做“最长连续序列”(Longest Continuous Increasing Subsequence),通常用C++或其他编程语言进行解答。这个题目的目的是找到一个给定整数数组中的最长递增子序列。递增子序列是数组中的一段连续元素,它们按顺序严格增大。 这里是一个简单的C++解决方案思路: ```cpp #include <vector> using namespace std; class Solution { public: int longestContinuousIncreasingSubsequence(vector<int>& nums) { if (nums.empty()) return 0; // 避免空数组的情况 int n = nums.size(); vector<int> dp(n, 1); // dp[i] 表示以nums[i]结尾的最长递增子序列长度 int max_len = 1; // 初始化最长递增子序列长度为1 for (int i = 1; i < n; ++i) { // 遍历数组,从第二个元素开始 if (nums[i] > nums[i-1]) { // 如果当前元素比前一个大 dp[i] = dp[i-1] + 1; // 更新dp值,考虑加入当前元素后的增长长度 max_len = max(max_len, dp[i]); // 检查是否更新了最长序列长度 } } return max_len; // 返回最长连续递增子序列的长度 } }; ``` 在这个代码中,我们使用了一个动态规划(Dynamic Programming)的方法,维护了一个数组`dp`来存储每个位置以该位置元素结尾的最大递增子序列长度。遍历过程中,如果遇到当前元素大于前一个元素,则说明可以形成一个新的递增子序列,所以将`dp[i]`设置为`dp[i-1]+1`,并更新全局的最长序列长度。 如果你想要深入了解这个问题,可以问: 1. 这个问题的时间复杂度是多少? 2. 动态规划是如何帮助解决这个问题的? 3. 如何优化这个算法,使其空间复杂度更低?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值