溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

LeetCode283. Move ZeroesC語言

發布時間:2020-06-16 11:40:55 來源:網絡 閱讀:391 作者:努力的C 欄目:編程語言
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:
You must do this in-place without making a copy of the array.
Minimize the total number of operations

題意:給一個數組,把其中的0放到最后。注意不要創建新的數組和最小化所有操作的數量

void moveZeroes(int* nums, int numsSize) {
    //選擇排序變一下。。。。。n*2
    // int i,j;
    // for(i=0;i<numsSize;i++)
    //   for(j=i+1;j<numsSize;j++){
    //       if(nums[i]==0){
    //           int temp=nums[i];
    //           nums[i]=nums[j];
    //           nums[j]=temp;
    //       }
    //   }
    
    //網上的做法1.簡單粗暴容易理解。只不過是分了兩步而已。。。
    int i;
    int index=0;
    for(i=0;i<numsSize;i++){
        if(nums[i]!=0){
            nums[index]=nums[i];
            index++;
    }
    }
    // printf("%d",index);
    for(i=index;i<numsSize;i++){
        nums[i]=0;
    }
    
    ///還有做法2.不太容易理解,
}

PS:維持倆指針。。。。。

一開始想到的事排序。。。。。。把0排到最后,雖然過了,但是復雜度n*2.操作數量也挺多的。

看了網上的做法1.容易理解簡單粗暴。

還有一個做法理解起來有點障礙。。。。。。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女