2016年1月29日 星期五

LEET code -Move Zeroes

 Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:


  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

找了半個小時的BUG 跟白癡依樣
left紀錄0的位置,right去找0右邊第一個出現非0的數字




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
void moveZeroes(int* nums, int numsSize) {
    int left=0,right=0,i=0;
    for( i=0;i<numsSize;i++){
        if(nums[i]!=0)continue;
        left=right=i;
        while(right<numsSize && nums[right]==0)right++;
        if(nums[left]==0 && nums[right]!=0  &&left<numsSize&&right<numsSize){
            int temp=nums[left];
            nums[left]=nums[right];
            nums[right]=temp;
        }
    }

沒有留言:

張貼留言