码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode283]Move Zeros将一个数组中为0的元素移至数组末尾

时间:2015-12-19 21:48:00      阅读:169      评论:0      收藏: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:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

思路:可以该数组从后向前遍历,遇到0就把0放至末尾;或者从前遍历遇到非0元素则依次放在数组前,最后将后边元素全部置为0

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LeetCode
{
    class MoveZerosSolution
    {
        public void MoveZeroes(int[] nums)
        {
            //O(n2)
            for (int i = nums.Length - 1; i >= 0; i--)
            {
                if (nums[i] == 0)
                {
                    for (int j = i; j < nums.Length - 1; j++)
                    {
                        nums[j] = nums[j + 1];
                    }
                    nums[nums.Length - 1] = 0;
                }

            }
            /*O(1)解法
        
            int index = 0;
            for(int i = 0;i < nums.Length;i++)
                if(nums[i] != 0)
                {
                    nums[index] = nums[i];
                    index++;
                }
            for(int j = index;j < nums.Length;j++)
                nums[j] = 0;
        
            */
        }
    }
}

 

[LeetCode283]Move Zeros将一个数组中为0的元素移至数组末尾

标签:

原文地址:http://www.cnblogs.com/zhangbaochong/p/5059725.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!