如何有效旋转数组?

编程入门 行业动态 更新时间:2024-10-11 07:36:05
本文介绍了如何有效旋转数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给定一个 n 整数数组和一个数字 d ,对数组执行左旋转。然后将更新后的数组打印为单行以空格分隔的整数。

Given an array of n integers and a number, d, perform left rotations on the array. Then print the updated array as a single line of space-separated integers.

样本输入:

5 4 1 2 3 4 5

5 4 1 2 3 4 5

第一行包含两个以空格分隔的整数,分别表示 n (整数的数量)和 d (您必须执行的左旋转次数)。 第二行包含 n 用空格分隔的整数,描述数组初始状态的各个元素。

The first line contains two space-separated integers denoting the respective values of n (the number of integers) and d (the number of left rotations you must perform). The second line contains n space-separated integers describing the respective elements of the array's initial state.

示例输出:

5 1 2 3 4

5 1 2 3 4

static void Main(String[] args) { string[] arr_temp = Console.ReadLine().Split(' '); int n = Int32.Parse(arr_temp[0]); int d = Int32.Parse(arr_temp[1]); string[] arr = Console.ReadLine().Split(' '); string[] ans = new string[n]; for (int i = 0; i < n; ++i) { ans[(i + n - d) % n] = arr[i]; } for (int j = 0; j < n; ++j) { Console.Write(ans[j] + " "); } }

如何使用较少的内存来解决此问题? / p>

How to use less memory to solve this problem?

推荐答案

在大多数情况下,这将使用较少的内存,因为第二个数组仅与移位一样大。

This will use less memory in most cases as the second array is only as big as the shift.

public static void Main(string[] args) { int[] n = { 1, 2, 3, 4, 5 }; LeftShiftArray(n, 4); Console.WriteLine(String.Join(",", n)); } public static void LeftShiftArray<T>(T[] arr, int shift) { shift = shift % arr.Length; T[] buffer = new T[shift]; Array.Copy(arr, buffer, shift); Array.Copy(arr, shift, arr, 0, arr.Length - shift); Array.Copy(buffer, 0, arr, arr.Length - shift, shift); }

更多推荐

如何有效旋转数组?

本文发布于:2023-11-30 06:59:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649099.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!