8ms simple C solution


  • 12
    H
    void moveZeroes(int* nums, int numsSize) {
        int totalZeros = 0;
        
        for(int i = 0; i < numsSize; i++) {
            if(nums[i] == 0) {
                totalZeros++;
            }
            else {
                nums[i - totalZeros] = nums[i];
            }
        }
        
        for(int i = (numsSize - totalZeros); i < numsSize; i++) {
            nums[i] = 0;
        }
    }

  • 0
    X

    very clever
    I suppose it can minimize the shift of non-zero elements


  • 0
    J

    good. but i use the same method, it costs 20ms


  • 0
    H

    @joe297 The same language?


  • 0
    L

    Nice! I came up with something very similar, but instead of doing a second loop I used a conditional assignment near the end of the first loop. It seems to run ~2ms faster this way (6ms was my result with 21 test cases):

    void moveZeroes(int* nums, int numsSize)
    {
    	int i, shift = 0;
    
    	for (i = 0; i < numsSize; i++) {
    		if (nums[i] == 0) {
    			shift++;
    			continue;
    		}
    
    		nums[i - shift] = nums[i];
    		if (shift)
    			nums[i] = 0;
    	}
    }
    

  • 1
    W

    similar ,6ms
    void moveZeroes(int* nums, int numsSize) {
    int idx = 0;

    for(int i = 0; i < numsSize; i++) {
        if(nums[i] != 0) {
            nums[idx++] = nums[i];
        }
    }
    
    for(int i = idx; i < numsSize; i++) {
        nums[i] = 0;
    }
    

    }


  • 0
    B

    @joe297 I did the exactly same thing in C++ and it costs me 16ms.


Log in to reply
 

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