My 4ms fast Java solution only using O(1) space


  • 0
    L
    public class Solution {
        public int longestConsecutive(int[] nums) {
            if(nums == null || nums.length == 0) {
                return 0;
            }
            int max = 1;
            int total = 1;
            Arrays.sort(nums);
            for(int i = 1; i < nums.length; i++) {
                if(nums[i] == nums[i - 1]) continue;
                else {
                    if(nums[i] == nums[i - 1] + 1) {
                    total += 1;
                    } else {
                        total = 1;
                    }
    
                    if(total > max) max = total;
                }
                
            }
            return max;
        }
    }
    

  • 0
    M

    The problem asks you to do it in O(n) time complexity. When you sort the array you already are at O(n log n) to say the least


Log in to reply
 

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