• Leetcode 283. 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.

    题目大意:

    给定一个数组nums,编写函数将数组内所有0元素移至数组末尾,并保持非0元素相对顺序不变。

    例如,给定nums = [0, 1, 0, 3, 12],调用函数完毕后, nums应该是 [1, 3, 12, 0, 0]。

    注意:

    1. 你应该“就地”完成此操作,不要复制数组。
    2. 最小化操作总数。

    思路:我们可以知道调用函数之后,某个非0数的位置肯定是小于等于它原来的位置的,初始化一个指针pos = 0,一个指针i从下标0开始遍历,每当nums[i] != 0, 就将其值赋给nums[pos],同时pos++.最后将下标从pos到numsSize-1对应的数组值赋值为0.

    再思考:每当nums[i] != 0,如果pos == i,就没有必要nums[pos] = nums[i],只需要pos++.如果pos != i,那么就应该nums[pos] = nums[i],这时我们可以将nums[i] = 0.最后pos++.

    C代码:

     1 void moveZeroes(int* nums, int numsSize) {
     2     int pos = 0, i;
     3     for(i = 0; i < numsSize; i++){
     4         if(nums[i] != 0){
     5             nums[pos] = nums[i];
     6             pos++;
     7         }
     8     }
     9     for(i = pos; i < numsSize; i++)
    10         nums[i] = 0;
    11 }
     1 void moveZeroes(int* nums, int numsSize) {
     2     int pos = 0, i;
     3     for(i = 0; i < numsSize; i++){
     4         if(nums[i] != 0){
     5             if(pos != i){
     6                 nums[pos] = nums[i];
     7                 nums[i] = 0;
     8             }
     9             pos++;
    10         }
    11     }
    12 }
  • 相关阅读:
    Android开发:系统自动实现开机启动
    Android高手进阶教程【转】
    android 各种控件颜色值
    Android开发博客国内最大的移动开发博客eoe移动开发者社区
    异步图片加载工具类
    Android中shape的使用
    Android的asset/res资源框架结构
    winddows 运行指令 (2)
    使用activeMQ实现jms
    ActiveMQ在C#中的应用
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/5837912.html
Copyright © 2020-2023  润新知