Why using sort is faster?


  • 0
    B
    public int longestConsecutive(int[] nums) {
            Arrays.sort(nums);
            int count = 1 ; 
            ArrayList<Integer> al = new ArrayList<Integer>();
            for(int i = 0 ; i < nums.length; i++) {
                // System.out.println(nums[i]);
                if(i == 0) {
                    al.add(1);
                }
                else if(nums[i] == nums[i-1]) {
                    al.add(count);
                }
                else if(nums[i] == nums[i-1] +1){
                    count ++;
                    al.add(count);
                }
                else {
                    count = 1;
                    al.add(count);
                }
            }
            int max = 0;
            for(int i = 0 ; i < al.size(); i++) {
                // System.out.println(al.get(i));
                if(al.get(i) > max) {
                    max = al.get(i);
                }
            }
            
            return max;
        }
    

    This takes 10ms. Bests 90% java program. The one uses Set takes 13 ms.


Log in to reply
 

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