zoukankan      html  css  js  c++  java
  • [Array]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.

    Credits:
    Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

    思路:将数组中所有的0移动到末尾,遍历数组nums,然后将非零值放进nums前面的位置,之后将后面的位置全部置0.

    优秀代码:

     1 void movezeroes(vector<int>& nums){
     2 int n = nums.size(), j = 0;
     3 for(size_t i = 0; i < n; i++){
     4 if(nums[i] != 0){
     5 nums[j++] = nums[i];
     6 }
     7 }
     8 for(;, j< n; j++){ //最前面的条件没有写,表示继续上面第一个for的j
     9 nums[j] = 0;
    10 }
    11 }
  • 相关阅读:
    iOS基础
    iOS基础
    iOS基础
    iOS基础
    iOS基础
    iOS基础
    iOS基础
    简单DP + 高精
    高精度计算
    树 (tree)
  • 原文地址:https://www.cnblogs.com/qinguoyi/p/7283390.html
Copyright © 2011-2022 走看看