算法系列——Move Zeroes

来源:互联网 发布:少女时代知乎话题 编辑:程序博客网 时间:2024/05/29 09:14

题目描述

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.

解题思路

题目要求将数组中的所有0元素放在数组后面,并保持 非0值的相对顺序不变。
最优的解法应该是时间复杂度O(n)且 空间复杂度为O(1)的解法,核心是,采用双索引 k,i在[0,k]区间的所有元素为非0值,i用来遍历数组,交换0元素和非0元素,直至数组末尾。

算法实现

public class Solution {    public void moveZeroes(int[] nums) {        int k=0;        int temp=0;        for(int i=0;i<nums.length;i++)            if(nums[i]!=0){                if(i!=k)                {                   temp=nums[k];                   nums[k]=nums[i];                   nums[i]=temp;                }                    k++;            }    }}
原创粉丝点击