zoukankan      html  css  js  c++  java
  • LeetCode 283. Move Zeroes

    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.

    总结:虽然是一道很简单的题目,但是想写出优雅的代码还是有难度的。一定要美美美!


    【java代码】

     1 public class Solution {
     2     public void moveZeroes(int[] nums) {
     3         if(nums == null || nums.length <= 1) return;
     4         
     5         int insertPos = 0;
     6         for(int num : nums) {
     7             if(num != 0) nums[insertPos++] = num;
     8         }
     9         
    10         while(insertPos < nums.length) {
    11             nums[insertPos++] = 0;
    12         }
    13     }
    14 }
  • 相关阅读:
    初始化类的对象时代码的执行顺序
    非原子的 64 位操作
    守护线程
    Redis
    Redis
    Redis
    Redis
    好听美文随手记
    往服务器数据库插入数据报错,在本地数据库测试却无错误。
    关于云服务器中发送邮件,出现无法从传输连接中读取数据:
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6490851.html
Copyright © 2011-2022 走看看