Skip to content
Snippets Groups Projects

Rotate Array

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Kiryuu Sakuya
    Program.cs 1.07 KiB
    using System;
    using System.Collections.Generic;
    
    namespace leetcodecsharp
    {
        class Program
        {
            // O(n^2) method
            //public static void Rotate(int[] nums, int k)
            //{
            //    for (int i = nums.Length; i > nums.Length - k; i--)
            //    {
            //        for (int j = nums.Length - 1; j > 0; j--)
            //        {
            //            int temp;
            //            temp = nums[j];
            //            nums[j] = nums[j - 1];
            //            nums[j - 1] = temp;
            //        }
            //    }
            //    Console.WriteLine("[{0}]", string.Join(", ", nums));
            //}
    
            public static void Rotate(int[] nums, int k)
            {
                k = k % nums.Length;
                Array.Reverse(nums, 0, nums.Length);
                Array.Reverse(nums, 0, k);
                Array.Reverse(nums, k, nums.Length - k);
            }
            public static void Main(string[] args)
            {
                int[] a = { 1, 2 };
                int b = 3;
                Rotate(a, b);
                Console.WriteLine("[{0}]", string.Join(", ", a));
            }
        }
    }
    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