My concise C++ code using DP algorithm.Just 11 lines.Beats 93.92% c++ submissions.


  • -4
    B

    class Solution {
    public:
    int longestConsecutive(vector<int>& nums) {

        if (nums.empty()) return 0;
    sort(nums.begin(), nums.end());
    int res=1, tempLen=1;
    for (int i = 1; i < nums.size(); i++)
    {
    	if (nums[i] == nums[i - 1] + 1) tempLen++;
    	else if (nums[i] == nums[i - 1]){}
    	else tempLen = 1;
    	if (tempLen > res) res = tempLen;
    }
    return res; 
    }
    

    };


  • 0

    Sort is O(nlogn), does not satisfy requirements


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.