[LeetCode][数论]Move Zeroes

来源:互联网 发布:上海海尚琴行淘宝 编辑:程序博客网 时间:2024/04/30 00:12

题目描述:

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开始,满足条件的话就将当前值赋值到所给的索引位置上,最后将剩余的位置补充为满足条件的值,本题中应补0


代码实现:

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


0 0
原创粉丝点击