• leetcode算法题-移动零


    题目

    给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

    示例:
    输入: [0,1,0,3,12]
    输出: [1,3,12,0,0]

    说明:
    1.必须在原数组上操作,不能拷贝额外的数组。
    2.尽量减少操作次数。

    作者:力扣 (LeetCode)
    链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x2ba4i/
    来源:力扣(LeetCode)

    我的解法

    class Solution {
        public void moveZeroes(int[] nums) {
            if(nums.length == 1){
                return;
            }
            int index = nums.length -1;
            while(nums[index] == 0 && index > 0){
                index--;
            }
            if(index == 0){
                return;
            }
            boolean mark = false;
            for (int i = 0; i <= index;i++ ) {
                if(nums[i] == 0){
                    for (int j = i; j < index; j++) {
                        int temp = nums[j];
                        nums[j] = nums[j+1];
                        nums[j+1] = temp;
                    }
                    index--;
                    mark = true;
                }
            }
            if(mark){
                moveZeroes(nums);
            }
        }
    }
    
    

    思路就是记住最后不是0的位置,每次将0移动到后面。代码比较繁琐且不易理解。

    官方解法

    void moveZeroes(vector<int>& nums) {
        int lastNonZeroFoundAt = 0;
        // If the current element is not 0, then we need to
        // append it just in front of last non 0 element we found. 
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] != 0) {
                nums[lastNonZeroFoundAt++] = nums[i];
            }
        }
        // After we have finished processing new elements,
        // all the non-zero elements are already at beginning of array.
        // We just need to fill remaining array with 0's.
        for (int i = lastNonZeroFoundAt; i < nums.size(); i++) {
            nums[i] = 0;
        }
    }
    
    

    以上为C++版本

    class Solution {
        public void moveZeroes(int[] nums) {
          int index = 0;
          for(int num:nums){
              if(num!=0){
                  nums[index++]=num;
              }
          }
          while(index<nums.length){
              nums[index++] = 0;
          }
        }
    }
    
    

    解题思路:
    遍历数组,无为0的元素移动数组前方,用index下标记录。
    遍历结束,对index值后的元素统一设为0。

    通俗易懂,看了一遍就理解了,相比之下我的解法真是太烂了。题解还是有非常多的解法值得学习!

  • 相关阅读:
    Spring--自定义注解
    IntelliJ IDEA实用插件
    Zero date value prohibited解决方法
    如何保证幂等性
    Map遍历的几种方式
    Static关键字
    索引失效 -- 使用Between范围查询时
    接口的不同写法在Swagger上的不同
    js与jquery获取input输入框中的值
    一个简单的 aiax请求例子
  • 原文地址:https://www.cnblogs.com/chwwww/p/14310462.html
Copyright © 2020-2023  润新知