zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    代码重构技术方法
    《算法导论》为什么经典
    BeagleBone Black教训四局:简单LED对照实验
    linux(Ubuntu)安装QQ2013
    ubuntu卸载qq2012
    android弧形进度条,有详细注释的,比较简单
    Android自定义进度条
    AndroidのUI设计研究(一)——自定义ProgressBar
    介绍几个工作开发中封装的好用的android自定义控件
    android自定义viewgroup之我也玩瀑布流
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/5837912.html
Copyright © 2011-2022 走看看