zoukankan      html  css  js  c++  java
  • [leetcode]283. Move Zeroes

    这是leetcode第283题

    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].

    题目意思,就是把数组中的0都移动到数组的末尾,在保持其他元素相对顺序不变的情况下。

    解题思路

    2次遍历数组

    第一次遍历,把不等于0的元素保存到另外一个数组中。
    第二次遍历,先把已保存不等于0的元素依次赋值到nums,然后把nums剩下的元素空位都赋值0

    public class Solution {
        public void moveZeroes(int[] nums) {
            ArrayList<Integer> nonZeroNumList = new ArrayList<>();
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] != 0) {
                    nonZeroNumList.add(nums[i]);
                }
            }
            for (int i = 0; i < nonZeroNumList.size(); i++) {
                nums[i] = nonZeroNumList.get(i);
            }
            for (int i = nonZeroNumList.size(); i < nums.length; i++) {
                nums[i] = 0;
            }
        }
    }
    

    1次遍历数组

    遍历过程有2个下标位偏移标记,分别是ij
    i代表对于nums当前元素的偏移标记;
    j代表遍历过程中,下一个不等于0的元素,应该存放在nums位置的偏移标记;

    public class Solution {
        public void moveZeroes(int[] nums) {
            for (int i = 0, j = 0; i < nums.length; i++) {
                if (nums[i] != 0) {
                    if (i != j) {
                        nums[j] = nums[i];
                        nums[i] = 0;
                    }
                    j++;
                }
            }
        }
    }
    
  • 相关阅读:
    Android 数据库框架 DBFlow 的使用
    Android进阶AIDL使用自定义类型
    Android进阶之AIDL的使用详解
    RecyclerView实现拖动排序和滑动删除功能
    RecyclerView的刷新分页
    RecyclerView 的 Item 的单击事件
    RecyclerView 的简单使用
    AutoCompleteTextView的简单使用
    Spinner的简单实用
    黎曼猜想
  • 原文地址:https://www.cnblogs.com/wingyip/p/5507089.html
Copyright © 2011-2022 走看看