My cpp solution using sort


  • -5
    S
    class Solution {
    public:
        int longestConsecutive(vector<int>& nums) {
            if(nums.size()==0) return 0;
            sort(nums.begin(),nums.end());
            int length = 1;
            int maxLength = 1;
            int value = nums[0];
            for(int i(1);i<nums.size();i++)
            {
                if(nums[i] == value+1)
                {
                    length++;
                    maxLength = max(maxLength,length);
                    value = nums[i];
                }else if(nums[i] != value)
                {
                    length = 1;
                    value = nums[i]; 
                }
            }
            return maxLength;
        }
    };

  • 0
    W

    Notice : Your algorithm should run in O(n) complexity.

    But your algorithm run in O(nlgn) as you sorted.


Log in to reply
 

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