zoukankan      html  css  js  c++  java
  • leetcode| Move Zeroes

    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:

    1. You must do this in-place without making a copy of the array.
    2. Minimize the total number of operations.

    题目:给你丫一数组,搞一个算法把0全移后头去,别复制数组,减少操作次数。。。

    思路:这题按照题意得要求想了很久也没什么思路,而后参考了一位同仁的c++版本,写的比较有风格,一行注释木有,我也就搞了个java版本的,以下,,,,

    public class Solution {
     public void moveZeroes(int[] nums) {

    //搞两个指针

      int i = 0;//指示最靠前的那个0的索引,迭代到0时,j+1,i不+1
      int j = 0;//指示当前迭代元素,每次+1
    //当两者不相等,说明之前那次操作是遇到0,我们只需要把当前元素跟前面的0交换之,0就后移了
      int len = nums.length;
      while(j<len){
        if(nums[j]!=0 ){
          if(i != j){//所以如果两者不相等,说明已然碰见一个这样的情况:当前索引前一位是0,当前索引后一位不是0
            nums[i++] = nums[j];
            nums[j] = 0;
          }else{
            i++;
          }
        }
        j++;
      }
    }
    }

  • 相关阅读:
    第一阶段冲刺第三天
    第一阶段冲刺第二天
    第一阶段冲刺第一天
    典型用户和场景
    第十周学习进度条
    第九周学习进度条
    会议视频
    课堂练习……找水王
    小组项目需求——NABCD
    第二阶段个人总结三
  • 原文地址:https://www.cnblogs.com/wujunjie/p/5670268.html
Copyright © 2011-2022 走看看