Java solution with O(nlogn) time and O(1) space


  • 0
    Y

    first sort the array and go through the array with a counter, if it is consecutive, we increase the counter and update max length, if the number is equal to the previous one, we do nothing, if not, we reset the counter to 1;

    public class Solution {
    public int longestConsecutive(int[] nums) {
    //corner case
    if(nums == null || nums.length == 0)
    return 0;
    if(nums.length < 2)
    return 1;
    Arrays.sort(nums);
    int max = 1 , count = 1;
    int num = nums[0];
    for(int i : nums){
    if(i == num + 1){
    count++;
    max = Math.max(max,count);
    }else if(i == num){
    continue;
    }else{
    count = 1;
    }
    num = i;
    }
    return max;
    }
    }


Log in to reply
 

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