Beats 100% JAVA solutions. Just sort & traverse.


  • -9
    B

    I don't quite understand why don't you just sort the array, and then traverse it. Could someone explain why you prefer to swap each element to its index position? Thanks a lot!

    public class Solution {
        public int firstMissingPositive(int[] nums) {
            if (nums.length==0){
                return 1;//will save much time than just sort(nums);
            }
            Arrays.sort(nums);
            int counter=0;
            for(int i=0;i<nums.length;i++){
                if(nums[i] == counter+1) counter++;
                if(nums[i] <= counter) continue;
                else break;
            }
            return counter+1;
        }
    }

  • 0
    M

    Because sorting an array takes O(nlogn). The requirement is O(n) time.


  • 0
    B

    Thanks a lot. I didn't see the requirements.


Log in to reply
 

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