First time my JAVA code beat 96.62%!!


  • -1
    Z

    代码如下:

    public static int longestConsecutive(int[] nums) {
            if (nums == null || nums.length == 0){
                return 0;
            }
            Arrays.sort(nums);
            int max = 1;
            int temp = 1;
            for (int i = 0; i < nums.length-1; i++) {
                if (nums[i+1] - nums[i] == 1){
                    temp++;
                }else if (nums[i+1] - nums[i] == 0){
                    continue;
                }else {
                    max = Math.max(max,temp);
                    temp=1;
                }
            }
            max = Math.max(max,temp);
            return max;
        }
    

  • 1
    Y

    @zhanglifeng Your solution is not quite right based on the requirement of this question.
    The question requires to deal with this problem in O(n) time, while Arrays.sort() in Java is done in a quick sort style, which is at least O(nlogn) in time complexity.
    But anyway, sorting the array could be a pretty straight-forward primitive idea.


  • 0
    Z

    @YaokaiYang Thank you ! it's indeed a error!


Log in to reply
 

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