Leetcode:283. 移动零

Leetcode:283. 移动零

题目描述

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

示例:

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

说明:

必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。

思路

思路1: 直接使用非零计数

直接使用遍历加非零计数进行替换操作,然后对最后为零的填零

思路2: 非零计数+替换

思路1方法若在大量零的情况下需要遍历两次,所以可以考虑使用两个指针交换数据

代码

代码1

class Solution {
    public void moveZeroes(int[] nums) {
        if (nums == null || nums.length == 0){
            return;
        }
        int notZeroIndex = 0;
        for(int i = 0; i < nums.length; i++){
            if (nums[i] != 0){
                nums[notZeroIndex++] = nums[i];
            }
        }
        for(int i = notZeroIndex; i < nums.length; i++){
            nums[i] = 0;
        }
    }
}

代码2:双指针+交换

class Solution {
    public void moveZeroes(int[] nums) {
        if (nums == null || nums.length == 0){
            return;
        }
        int notZeroIndex = 0;
        for(int i = 0; i < nums.length; i++){
            if(nums[i] != 0){
                swap(nums, i, notZeroIndex++);
            }
        }
    }
    
    private void swap(int[] nums, int i, int j){
        if (i == j){
            return;
        }
        nums[i] = nums[i] + nums[j];
        nums[j] = nums[i] - nums[j];
        nums[i] = nums[i] - nums[j];
    }
}

复杂度分析

思路1:直接使用非零计数

时间复杂度

$O(n)$

空间复杂度

$O(1)$

思路2

同上,但是时间复杂度在最坏情况下要比思路1优


文章作者: 小风雷
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小风雷 !
评论
 上一篇
Leetcode:384.打乱数组 Leetcode:384.打乱数组
Leetcode: 384.打乱数组题目描述打乱一个没有重复元素的数组。 示例:// 以数字集合 1, 2 和 3 初始化数组。 int[] nums = {1,2,3}; Solution solution = new
2020-03-27
下一篇 
Leetcode:217. 存在重复元素 Leetcode:217. 存在重复元素
Leetcode:217. 存在重复元素题目描述给定一个整数数组,判断是否存在重复元素。 如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。 示例 1:输入: [1,2,3,1] 输出:
2020-03-26
  目录