Runtime: 1 ms,but beats 17.62% of java submissions. why?


  • 0
    Y
    public class Solution {
        public void moveZeroes(int[] nums) {
            if(nums==null || nums.length==0)
                  return;
            int len = nums.length;
            int id = 0;
            for(int i=0;i<len;i++){
                if(nums[i]!=0){
                    nums[id++] = nums[i];
                }
            }
            for(int i=id;i<len;i++){
                nums[i] = 0;
            }
        }
    }
    

  • 0
    A

    This solution made a lot of unnecessary swap when nums[id++] and nums[i] both not 0. And 1 ms is actually not so good under this question because there are many 0ms answers. For example, mine is:

    public void moveZeroes(int[] nums) {
            if(nums.length == 0 || nums == null) return;
    	int most_left_0 = -1;
    	for(int i = 0; i<nums.length;i++){
    		if(nums[i] == 0){
    			most_left_0 = i;
    			break;
    		}
    	}
    	if(most_left_0 == -1) return;
    		
    	for(int j = most_left_0+1; j<nums.length; j++){
    		if(nums[j] != 0){
    			nums[most_left_0] = nums[j];
    			nums[j] = 0;
    			most_left_0++;
    		}
    	}
    }
    

Log in to reply
 

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