leetcode 189 旋转数组 c# 数组

 

看了旋转的步骤就很明显了,每次只需要移动一个位置到最前面。   ————经过验证,真的不是一般的麻烦,请舍弃。

              天了噜——原来这样更容易:  

方法一:建一个list<int>  追加两段内容输出即可。(临时空间)

        static void Main(string[] args)
        {
            int[] tst = new int[] { 1, 2, 3, 4, 5, 6 };
            int t = 2;
            List<int> tstt= ReturnU(tst, t);
            for (int i = 0; i < tst.Length; i++)
            {
                Console.WriteLine(tstt[i]); 
            }
            Console.ReadKey();
        }
        public static List<int> ReturnU(int[] nums, int count)
        {
            //新建一个数组将数组倒序存入count个值。
            List<int> list = new List<int>();
            for (int j = nums.Length - 1; j > nums.Length - (nums.Length - count-1); j--)
            {
                list.Add(nums[j]); 
            }
            //将剩下的内容填充到数组
            for (int i = 0; i < nums.Length-count; i++)
            {
                list.Add(nums[i]);
            }
            return list;
        }

 那么问题来了,既然叫做旋转数组,就不能“背道而驰”否则偏离了出题者想要考察的内容。

方法二: 旋转数组   --先起个响亮点的名字,假装自己已经做出来了,并且答案如下。

        当我抬头仰望星空的那一霎那,我看见一只5毫米长的蚊子飞了进来,我眼眶突然湿润了,因为我知道了答案。题目就在答案,带我在vs上去实现。(无厘头)

            做了好久,终于做出来了,利用Array.Reverse() 这个反转的函数。

        //旋转数组方式二:翻转数组
        public static void ReturnUs(int[] nums, int count)
        {
            Array.Reverse(nums, nums.Length - count, nums.Length - (nums.Length - count));//翻转尾巴 
            Array.Reverse(nums, 0, nums.Length - count);//翻转头 
            Array.Reverse(nums); //翻身
        }

猜你喜欢

转载自blog.csdn.net/us2019/article/details/80251197
今日推荐