zoukankan      html  css  js  c++  java
  • 【LintCode题集】Q539

    【Q539】

    描述

      给一个数组 nums 写一个函数将 0 移动到数组的最后面,非零元素保持原数组的顺序

      1.必须在原数组上操作

      2.最小化操作数

      样例:

      给出 nums = [0, 1, 0, 3, 12], 调用函数之后, nums = [1, 3, 12, 0, 0].

    思路

      函数原型

    1 public void moveZeroes(int[] nums) {}

      从函数原型可以看出,此题目是在原数组上进行操作,所以这个题目可以变为,先删除为0的元素,然后在后面补0.

    实现

     1 public void moveZeroes(int[] nums) {
     2         // Write your code here
     3         
     4         
     5         
     6         // Write your code here
     7 
     8         int size = nums.length;
     9         int insertIndex = 0 ;  //即将插入的索引号
    10 
    11         for(int i = 0 ; i < size ; i ++){
    12             if(nums[i] == 0 ){
    13                 continue;
    14             }
    15 
    16             else{
    17                 nums[insertIndex] = nums[i];
    18                 insertIndex ++ ;
    19             }
    20         }
    21 
    22 
    23         for(int i = 0 ; i < ( size - insertIndex ) ; i ++){
    24             nums[size - 1 - i] = 0 ;
    25         }
    26 
    27       
    28 }
  • 相关阅读:
    Java-判断一个数是不是素数
    Sublime快捷键
    python
    全排列
    python
    python
    OpenCV 实现图像结构相似度算法 (SSIM 算法)
    C++
    C++
    NFA 转 DFA
  • 原文地址:https://www.cnblogs.com/tancky/p/6575108.html
Copyright © 2011-2022 走看看