4ms Beats 97% two-pointer solution


  • 0
    S
    public int longestConsecutive(int[] nums) {
    	if (nums.length == 0) return 0;
            Arrays.sort(nums);
    	int max = 0, start = 0, end = 0;
    	while (++end < nums.length) {
    		if (nums[end] == nums[end-1]){
    			start++;
    		}else if (nums[end] != nums[end-1]+1){
    			max = Math.max(max, end-start);
    			start = end;
    		} 
    	}
    	return Math.max(max, end-start);
    }
    

  • 0
    W

    @shawloatrchen "Arrays.sort(nums);" makes it O(n log n). The problem description explicitely asks for an O(n) solution.


  • 0
    S

    @windheuser oh my god, thanks for you reminder


Log in to reply
 

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