LeetCode 128.最长连续序列

直接暴力破解出来的结果就挺不错,时空效率击败90%以上,先用sort将数组排序,再从头开始找最大连续长度即可,注意不用set的话,有重复数字,不能计入长度

#include 
#include 
#include 
#include 
#include 
using namespace std;

/*
* 思路:首先考虑暴力解法,先将数组排序,再计算最长连续长度
*/

class Solution {
public:
    int longestConsecutive(vector& nums) {
        if (nums.size() == 0)
            return 0;
        sort(nums.begin(), nums.end());
        int max_len = 1, last = nums[0];
        for (int i = 1; i < nums.size(); )
        {
            int len = 1, j = i;
            // 找连续序列,可能有重复数
            while (j < nums.size() && (last == nums[j] || last + 1 == nums[j]))
            {
                if (last != nums[j])
                {
                    last = nums[j];
                    len++;
                }
                j++;
            }
            if (i == j)
                i++;
            else i = j;
            last = nums[i - 1];
            max_len = max(max_len, len);
        }
        return max_len;
    }
};


int main()
{
    vectornums;
    int n, a;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> a;
        nums.push_back(a);
    }
    Solution A;
    cout << A.longestConsecutive(nums) << endl;
}

你可能感兴趣的:(LeetCode,c++,leetcode,算法)