[LeetCode] 283. 移动零

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

例如, 定义 nums = [0, 1, 0, 3, 12],调用函数之后, nums 应为 [1, 3, 12, 0, 0]。

注意事项:

1、必须在原数组上操作,不要为一个新数组分配额外空间。
2、 尽量减少操作总数。

英文

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.

Java

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

推荐阅读更多精彩内容