283. Move Zeroes

Description

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:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.

Solution

Two-pointers

class Solution {
    public void moveZeroes(int[] nums) {
        if (nums == null || nums.length == 0) {
            return;
        }
        
        int j = 0;
        for (int i = 0; i < nums.length; ++i) {
            if (nums[i] != 0) {
                swap(nums, i, j++);
            }
        }
    }
    
    private void swap(int[] nums, int i, int j) {
        if (i == j) {
            return;
        }
        
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,776评论 0 33
  • 11月21日,我走进老显咖啡厅,跟一群小伙伴一起喝咖啡。 你问我, 咖啡好喝吗?咖啡馆环境怎么样?在咖啡馆碰到了什...
    丽萍1阅读 231评论 1 0
  • 还是无法根据基础去想像,只能照书画
    长弓心悦阅读 217评论 0 2
  • 来看“天才达·芬奇” 世界巡展是广州八月的某个雨天。以前,对达芬奇的认识只停留在几幅人人皆知的名画,和因《达芬奇密...
    诗云SY阅读 652评论 6 2
  • 岁月不饶人,可我绕不了它,这光阴里所有的痛与凉,焦急如它又怎么能懂。
    RYXXZ阅读 161评论 0 0