• Move Zeroes (算法)


    好吧,其实这道题刚开始就有大体思路了,但是因为指针命名的混乱,导致逻辑顺序不清晰。初次写的代码对连续0的情况不能很好的处理。

    后来吃晚饭的路上又想了想,把想清楚的思路发到手机上,吃完饭回来一下子就做出来了/(ㄒoㄒ)/~~ 因此记录一下。

    题目

    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.

    TAGS

    Array   Two Pointers

    代码

     1  1 public class Solution {
     2  2     public void moveZeroes(int[] nums) {
     3  3         int len =nums.length;
     4  4         int pt1=0,pt2=0;
     5  5         while(pt2<len){//pt1指向0,pt2逐渐移动
     6  6             if(nums[pt1]==0){
     7  7                 if(nums[pt2]!=0){
     8  8                     nums[pt1]=nums[pt2];
     9  9                     nums[pt2]=0;
    10 10                     pt1++;
    11 11                 }
    12 12             }else{
    13 13                 pt1++;
    14 14             }
    15 15             pt2++;
    16 16         }
    17 17     }
    18 18 }
    __________________________________________________________ shoobie do lang lang ^^
  • 相关阅读:
    Swift
    UIWindow 详解及使用场景
    点击状态栏回到顶部的功能失效的解决办法
    iOS
    从经典问题来看 Copy 方法
    从汇编层面深度剖析C++虚函数
    数值的整数次方
    求整数二进制中1的个数
    C++中的位运算总结
    嵌入在C++程序中的extern "C"
  • 原文地址:https://www.cnblogs.com/annaivsu/p/5644939.html
Copyright © 2020-2023  润新知