539移动零

来源:互联网 发布:ubuntu 访问网络命令 编辑:程序博客网 时间:2024/05/21 21:35

给一个数组 nums 写一个函数将 0 移动到数组的最后面,非零元素保持原数组的顺序
思路:
1.两个索引,一个0,一个非零,零跟非零互换(互换函数swap(a,b))
2.零索引在非零索引之前
法1:

public class Solution {    /**     * @param nums an integer array     * @return nothing, do this in-place     */    public void moveZeroes(int[] nums) {        // Write your code here        int j=0;        for(int i=0;i<nums.length;i++){            if(nums[i]==0){                int k=i+1;                while(k<nums.length){                    if(nums[k]==0)                    {                        k++;                    }                    else                    {                        j=nums[k];                        nums[i]=j;                        nums[k]=0;                        k++;                        break;                    }                }            }        }    }}

法2:非零向前移动——更快

public class Solution {    /**     * @param nums an integer array     * @return nothing, do this in-place     */    public void moveZeroes(int[] nums) {        // Write your code here        int one = 0;        int fast = 0;        int n = nums.length;        int x = 0;        for(int i=0;i<n;i++){            if(nums[i]!=x) { // 不为0 的向前移动                nums[one] = nums[i];                one++;            }        }        for(int i= one;i<n;i++) // 后面的就是0            nums[i] = x;    }}
0 0
原创粉丝点击