• leetcode- Move Zeros


    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扔到后边不一样,非0数的整体顺序是不变的!!!

    代码:

    package leetcode;

    public class MoveZeros {

        /*public void moveZeroes(int[] nums) {                   
            int len = nums.length;
            if (len == 1)
                return;
            int p1 = 0;
            int p2 = len - 1;
            while (p1 <= p2) {
                if (nums[p1] == 0) {
                    if (nums[p2] == 0) {
                        p2--;
                    } else {
                        nums[p1] = nums[p2];
                        nums[p2] = 0;
                        p2--;
                    }
                } else {
                    p1++;
                }
            }

        }*/
        public void moveZeroes(int[] nums){             //思路:设置两个指针
            int len = nums.length;
            if(len == 1 ) return ;
            int p1 = 0;
            int p2 = 0;
            while(p2 < len){
                if(nums[p2] != 0){
                    int tmp = nums[p1];
                    nums[p1] = nums[p2];             //这里不能直接赋0;
                    nums[p2] = tmp;
                    p1++;
                    p2++;
                }else{
                    p2++;
                }
            }
        }

        public static void main(String[] args) {
            // TODO Auto-generated method stub

        }

    }

    态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
  • 相关阅读:
    局部加权回归、欠拟合、过拟合(Locally Weighted Linear Regression、Underfitting、Overfitting)
    损失函数(Loss Function)
    线性回归、梯度下降(Linear Regression、Gradient Descent)
    从BSP模型到Apache Hama
    Apache Hama安装部署
    C#中的面向对象编程
    0<Double.MIN_VALUE
    Java方法的参数传递方式为: 值传递
    数据取对数的意义
    UBuntu安装配置记录
  • 原文地址:https://www.cnblogs.com/neversayno/p/5395111.html
Copyright © 2020-2023  润新知