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

        }

    }

    态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
  • 相关阅读:
    Information retrieval (IR class2)
    HTML随笔
    Evaluating Automatically Generated timelines from the Web (paper1)
    Kali 2020.1版本安装
    SystemTap
    Linux之IDIDID
    调试&内核探针
    Return-to-dl-resolve
    转载!
    一张图系列之函数重定位
  • 原文地址:https://www.cnblogs.com/neversayno/p/5395111.html
Copyright © 2011-2022 走看看