zoukankan      html  css  js  c++  java
  • 移动零

    给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

    示例:

    输入: [0,1,0,3,12]
    输出: [1,3,12,0,0]

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/move-zeroes                 https://leetcode.com/problems/move-zeroes
     

    class Solution {
        public void moveZeroes(int[] nums) {
            //判断是否有零 
            //将nums[i]不等于零的元素移动到前面
            int j = 0 ;
            for (int i = 0 ; i< nums.length ; i++) {
               if (nums[i] != 0){
                 nums[j] = nums[i];
                  if(j != i ){
                    nums[i] = 0;
                  }
                 j++; //在循环内执行
               }          
            }   
        }
    }
    public void moveZeroes(int[] nums) {
            if(nums == null || nums.length <=1)
                return;
            int last = -1;
            for(int i=0; i<nums.length; i++){
                if(nums[i] != 0){
                    nums[++last] = nums[i];
                    if(i != last)
                        nums[i]=0; 
                }
            }
        } 
    class Solution {
        public void moveZeroes(int[] nums) {
            int pos = 0;
            for(int i = 0;i < nums.length;i++) {
                if(nums[i] != 0) {
                    if(i != pos) {
                        nums[pos] = nums[i];
                        nums[i] = 0;
                    }
                    pos++;
                }
            }
        }
    }
  • 相关阅读:
    堆排序回顾
    动画函数封装
    mouseenter 和mouseover的区别
    元素滚动 scroll 系列
    元素可视区 client 系列
    元素偏移量 offset 系列
    JS执行机制
    BOM
    常用键盘事件
    常用鼠标事件
  • 原文地址:https://www.cnblogs.com/try-chi/p/11995704.html
Copyright © 2011-2022 走看看