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 }
  • 相关阅读:
    1219 总结
    1206 冲刺三
    1130 冲刺2
    1128 主页面
    1123 冲刺3
    1121 冲刺2
    1118 冲刺1
    1117 新冲刺
    0622 软件工程总结
    0617 实验四 主存空间的分配和回收
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6490851.html
Copyright © 2011-2022 走看看