Skip to content
Snippets Groups Projects

Move Zeroes

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Kiryuu Sakuya
    Program.cs 838 B
    using System;
    using System.Collections.Generic;
    
    namespace test
    {
        class Program
        {
            public static void MoveZeroes(int[] nums)
            {
                if (nums.Length == 1)
                    return;
                // 检查该数字之前是否是 0,如果是则与它交换
                for (int j = 0; j < nums.Length; j++)
                {
                    for (int i = 1; i < nums.Length; i++)
                    {
                        if (nums[i - 1] == 0)
                        {
                            nums[i - 1] = nums[i];
                            nums[i] = 0;
                        }
                    }
                }
            }
            public static void Main(string[] args)
            {
                int[] a = { 0, 1, 0, 3, 12 };
                MoveZeroes(a);
                Console.WriteLine("[{0}]", string.Join(", ", a));
            }
    
        }
    }
    • 最好的方法是,遍历数列,检测到非零就把它移动到前面来,过完一遍数列之后后面全部补上 0。

    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment