IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]LeetCode-- Move Zeroes

    csharp25发表于 2015-12-02 10:28:06
    love 0
    题目描述:


    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:
    You must do this in-place without making a copy of the array.
    Minimize the total number of operations.


    将数组中所有的0放在最后。


    思路:
    Two Pointer 解法。
    两个索引:z和nZ,分别表示等于0和不等于0的位置,初始化为0。
    扫一遍数组(nZ递增),遇到不等于0的,nums[nZ]与nums[z]互换,z++。


    实现代码:


    public class Solution {
        public void MoveZeroes(int[] nums) {
                 var nZ = 0;
        	    var z = 0;
        	   while(nZ < nums.Length)
        	   {
        	   		if(nums[nZ] != 0)
        			{
        				var t = nums[z];
        				nums[z] = nums[nZ];
        				nums[nZ] = t;
        				z++;
        			}
        			nZ++;
        	   }
        }
    }




沪ICP备19023445号-2号
友情链接