My Java solution beats 96.74%


  • 0
    W
    public class Solution {
        public int longestConsecutive(int[] nums) {
            if (nums == null || nums.length == 0) {
                return 0;
            }
            
            Arrays.sort(nums); //sort the array
            int bst = 1;
            int ans = 1;
            for (int i = 1; i < nums.length; ++i) {
                if (nums[i] - 1 == nums[i - 1]) {
                    ++ans;
                } else if (nums[i] == nums[i - 1]) {
                    // if case is [0, 1, 1, 2]
                    continue;
                } else {
                    if (ans > bst) {
                        bst = ans;
                    }
                    ans = 1;
                }
            }
            if (ans > bst) {
                bst = ans;
            }
            
            return bst;
        }
    }
    

Log in to reply
 

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