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 }
  • 相关阅读:
    bootstrap添加模态窗后,再弹出消息提示框后,原先的滚动条消失
    改变input[type=file]的默认样式
    javascript判断访问终端,手机端自动跳转
    sublime安装插件autoprefixer
    android 自动化压力测试-monkey 1 实践
    python 网络编程-TCP/UDP
    python 正则表达式
    Python 读写excel数据
    Python 删除列表中的重复数据
    Python python 基本语法
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/5837912.html
Copyright © 2011-2022 走看看