栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LeetCode:283. 移动零(java)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode:283. 移动零(java)

 方法1:加一个数组——以空间换时间
class Solution {
    public void moveZeroes(int[] nums) {
         // 1.将结果放入新数组res
         int len=nums.length;
         int[] res=new int[len];
         int i=0;
         int j=len-1;
         int pos=0;
         while(i<=j){
             if(nums[pos]==0)    res[j--]=0;
             else    res[i++]=nums[pos];
             pos++;
         }
         System.arraycopy(res,0,nums,0,len);
         // nums=Arrays.copyOf(res,len);//在编译器输出nums值以及改变,但在平台上nums没有被res赋值
    }
}

方法2:这个方法有点傻,其实遇到0,其后的所有值不用全都挪动的
class Solution {
    public void moveZeroes(int[] nums) {
        // 2.遇到零则直接移动,最后结尾空位0值填充
        int len=nums.length;
        int count=0;
        int i=0;
        while(i 

方法3:双指针(遍历两次)

两次遍历:遇到0,直接覆盖;然后在数组末尾补0

class Solution {
    public void moveZeroes(int[] nums) {
        // 3.双指针(两次遍历),遇到0,直接覆盖;然后在数组末尾补0
        int len=nums.length;
        int j=0;
        for(int i=0;i 

 

方法4:双指针(单次遍历)

 0值和非0值作替换

class Solution {
    public void moveZeroes(int[] nums) {
        // 4.双指针(单次遍历),0值和非0值作替换
        int len=nums.length;
        int j=0;
        int tmp;
        for(int i=0;i 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/847713.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号