Beats 100% JAVA solutions. Just sort & traverse.

  • -9

    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);
            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

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

  • 0

    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.