zoukankan      html  css  js  c++  java
  • 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

        }

    }

    态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
  • 相关阅读:
    php实现base64图片上传方式实例代码
    Html5 js FileReader接口
    获取月份
    JS实现双击编辑可修改
    SimpleMDE编辑器 + 提取HTML + 美化输出
    基于visual Studio2013解决C语言竞赛题之0608水仙花函数
    基于visual Studio2013解决C语言竞赛题之0607strcpy
    基于visual Studio2013解决C语言竞赛题之0605strcat
    android --静默安装
    基于visual Studio2013解决C语言竞赛题之0604二维数组置换
  • 原文地址:https://www.cnblogs.com/neversayno/p/5395111.html
Copyright © 2011-2022 走看看