您现在的位置是:首页 > 后台技术 > 数据结构与算法数据结构与算法

移动零(图文)

第十三双眼睛2024-01-22【数据结构与算法】人已围观

简介给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作

思路1:
从头到尾遍历数组,如果遇到一个为零的元素,就去后面遍历,找一个不为0的元素来交换,直到遍历完整个数组。代码如下:
public static void method1(int[] nums) {
    if (nums == null || nums.length ==0) {
        return;
    }
    for (int i = 0; i < nums.length; i ++) {
        if (nums[i] == 0) {
            for (int j = i + 1; j < nums.length; j ++) {
                if (nums[j] != 0) {
                    int temp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = temp;
                    break;
                }
            }
        }
    }
}

思路2:上面的方法,会嵌套循环,可以换一种思路,定义两个指针,一个记录已经处理过的位置,一个记录后面要处理的位置,遍历数组,左边的指针一定是已经处理过的,每循环一次,就判断右边指针的元素是不是0,如果不是0,就和左边的指针交换位置,并且两个指针都后移一位,如果是0,则左边的指针不动,右边的指针后移动一位,直到循环完毕。代码如下:
public static void method2(int[] nums) {
    if (nums == null || nums.length ==0) {
        return;
    }
    int length = nums.length;
    int left = 0;
    int right = 0;
    while (right < length){
        if(nums[right] != 0) {
            exchange(nums, left, right);
            left ++;
            right ++;
        } else {
            right ++;
        }
    }
}
public static void exchange(int[] nums, int left, int right) {
    int temp = nums[left];
    nums[left] = nums[right];
    nums[right] = temp;
}




 

Tags:

很赞哦! ()

文章评论

    共有条评论来说两句吧...

    用户名:

    验证码:

本站推荐

站点信息

  • 网站名称:JavaStudy
  • 建站时间:2019-1-14
  • 网站程序:帝国CMS7.5
  • 文章统计242篇文章
  • 标签管理标签云
  • 统计数据百度统计
  • 微信公众号:扫描二维码,关注我们