在 c# 中旋转列表的最简单方法
本文关键字:最简单 方法 列表 旋转 | 更新日期: 2023-09-27 18:29:43
列表说我有一个列表List<int> {1,2,3,4,5}
旋转意味着:
=> {2,3,4,5,1} => {3,4,5,1,2} => {4,5,1,2,3}
也许旋转不是最好的词,但希望你明白我的意思
我的问题,最简单的方法是什么(在短代码中,c# 4 Linq 就绪(,并且不会受到性能(合理性能(的影响
谢谢。
List<T>
最简单的方法(对于List<T>
(是使用:
int first = list[0];
list.RemoveAt(0);
list.Add(first);
性能虽然令人讨厌 - O(n(。
数组
这基本上相当于List<T>
版本,但更手动:
int first = array[0];
Array.Copy(array, 1, array, 0, array.Length - 1);
array[array.Length - 1] = first;
LinkedList<T>
如果您可以使用LinkedList<T>
,那会简单得多:
int first = linkedList.First;
linkedList.RemoveFirst();
linkedList.AddLast(first);
这是 O(1(,因为每个操作都是恒定时间。
Queue<T>
cadrell0 使用队列的解决方案是单个语句,因为Dequeue
删除元素并返回它:
queue.Enqueue(queue.Dequeue());
虽然我找不到任何关于其性能特征的文档,但我希望使用数组和索引作为"虚拟起点"来实现Queue<T>
- 在这种情况下,这是另一个 O(1( 解决方案。
请注意,在所有这些情况下,您都需要先检查列表是否为空。(您可以认为这是一个错误或无操作。
您可以将其实现为队列。取消排队和排队相同的值。
**我不确定将列表转换为队列的性能,但人们投票支持我的评论,所以我将其作为答案发布。
我使用这个:
public static List<T> Rotate<T>(this List<T> list, int offset)
{
return list.Skip(offset).Concat(list.Take(offset)).ToList();
}
似乎一些回答者将此视为探索数据结构的机会。 虽然这些答案内容丰富且有用,但它们并不是很Linq'ish。
Linq'ish 的方法是:你得到一个扩展方法,它返回一个惰性的 IEnumerable,它知道如何构建你想要的东西。 此方法不会修改源,应仅在必要时分配源的副本。
public static IEnumerable<IEnumerable<T>> Rotate<T>(this List<T> source)
{
for(int i = 0; i < source.Count; i++)
{
yield return source.TakeFrom(i).Concat(source.TakeUntil(i));
}
}
//similar to list.Skip(i-1), but using list's indexer access to reduce iterations
public static IEnumerable<T> TakeFrom<T>(this List<T> source, int index)
{
for(int i = index; i < source.Count; i++)
{
yield return source[i];
}
}
//similar to list.Take(i), but using list's indexer access to reduce iterations
public static IEnumerable<T> TakeUntil<T>(this List<T> source, int index)
{
for(int i = 0; i < index; i++)
{
yield return source[i];
}
}
用作:
List<int> myList = new List<int>(){1, 2, 3, 4, 5};
foreach(IEnumerable<int> rotation in myList.Rotate())
{
//do something with that rotation
}
这个怎么样:
var output = input.Skip(rot)
.Take(input.Count - rot)
.Concat(input.Take(rot))
.ToList();
其中rot
是要旋转的点数 - 必须小于input
列表中的元素数。
正如@cadrell0答案所示,如果这就是您对列表所做的一切,您应该使用队列而不是列表。
我的解决方案可能太基本了(我不想说它很蹩脚......(而不是 LINQ'ish。
但是,它具有相当不错的性能。
int max = 5; //the fixed size of your array.
int[] inArray = new int[5] {0,0,0,0,0}; //initial values only.
void putValueToArray(int thisData)
{
//let's do the magic here...
Array.Copy(inArray, 1, inArray, 0, max-1);
inArray[max-1] = thisData;
}
试试
List<int> nums = new List<int> {1,2,3,4,5};
var newNums = nums.Skip(1).Take(nums.Count() - 1).ToList();
newNums.Add(nums[0]);
虽然,我更喜欢乔恩·斯基特的回答。
我的数组解决方案:
public static void ArrayRotate(Array data, int index)
{
if (index > data.Length)
throw new ArgumentException("Invalid index");
else if (index == data.Length || index == 0)
return;
var copy = (Array)data.Clone();
int part1Length = data.Length - index;
//Part1
Array.Copy(copy, 0, data, index, part1Length);
//Part2
Array.Copy(copy, part1Length, data, 0, index);
}
我为此使用了以下扩展:
static class Extensions
{
public static IEnumerable<T> RotateLeft<T>(this IEnumerable<T> e, int n) =>
n >= 0 ? e.Skip(n).Concat(e.Take(n)) : e.RotateRight(-n);
public static IEnumerable<T> RotateRight<T>(this IEnumerable<T> e, int n) =>
e.Reverse().RotateLeft(n).Reverse();
}
它们当然很容易(OP 标题请求(,并且它们具有合理的性能(OP 写请求(。下面是我在 LINQPad 5 中在一台高于平均水平的笔记本电脑上运行的一个小演示:
void Main()
{
const int n = 1000000;
const int r = n / 10;
var a = Enumerable.Range(0, n);
var t = Stopwatch.StartNew();
Console.WriteLine(a.RotateLeft(r).ToArray().First());
Console.WriteLine(a.RotateLeft(-r).ToArray().First());
Console.WriteLine(a.RotateRight(r).ToArray().First());
Console.WriteLine(a.RotateRight(-r).ToArray().First());
Console.WriteLine(t.ElapsedMilliseconds); // e.g. 236
}
您可以使用以下代码进行左旋转。
List<int> backUpArray = array.ToList();
for (int i = 0; i < array.Length; i++)
{
int newLocation = (i + (array.Length - rotationNumber)) % n;
array[newLocation] = backUpArray[i];
}
你可以在.net框架中玩得很好。
我知道你想做的更像是一种迭代行为,而不是一个新的集合类型;所以我建议你尝试这个基于 IEnumerable 的扩展方法,它将适用于集合、列表等......
class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7 };
IEnumerable<int> circularNumbers = numbers.AsCircular();
IEnumerable<int> firstFourNumbers = circularNumbers
.Take(4); // 1 2 3 4
IEnumerable<int> nextSevenNumbersfromfourth = circularNumbers
.Skip(4).Take(7); // 4 5 6 7 1 2 3
}
}
public static class CircularEnumerable
{
public static IEnumerable<T> AsCircular<T>(this IEnumerable<T> source)
{
if (source == null)
yield break; // be a gentleman
IEnumerator<T> enumerator = source.GetEnumerator();
iterateAllAndBackToStart:
while (enumerator.MoveNext())
yield return enumerator.Current;
enumerator.Reset();
if(!enumerator.MoveNext())
yield break;
else
yield return enumerator.Current;
goto iterateAllAndBackToStart;
}
}
- 合理的性能
- 灵活
如果要更进一步,请创建一个CircularList
并按住相同的枚举器,以便在像在示例中一样旋转时跳过Skip()
。
下面是我的方法。谢谢
public static int[] RotationOfArray(int[] A, int k)
{
if (A == null || A.Length==0)
return null;
int[] result =new int[A.Length];
int arrayLength=A.Length;
int moveBy = k % arrayLength;
for (int i = 0; i < arrayLength; i++)
{
int tmp = i + moveBy;
if (tmp > arrayLength-1)
{
tmp = + (tmp - arrayLength);
}
result[tmp] = A[i];
}
return result;
}
public static int[] RightShiftRotation(int[] a, int times) {
int[] demo = new int[a.Length];
int d = times,i=0;
while(d>0) {
demo[d-1] = a[a.Length - 1 - i]; d = d - 1; i = i + 1;
}
for(int j=a.Length-1-times;j>=0;j--) { demo[j + times] = a[j]; }
return demo;
}
使用 Linq,
List<int> temp = new List<int>();
public int[] solution(int[] array, int range)
{
int tempLength = array.Length - range;
temp = array.Skip(tempLength).ToList();
temp.AddRange(array.Take(array.Length - range).ToList());
return temp.ToArray();
}
如果你正在使用一个字符串,你可以使用ReadOnlySpans非常有效地做到这一点:
ReadOnlySpan<char> apiKeySchema = "12345";
const int apiKeyLength = 5;
for (int i = 0; i < apiKeyLength; i++)
{
ReadOnlySpan<char> left = apiKeySchema.Slice(start: i, length: apiKeyLength - i);
ReadOnlySpan<char> right = apiKeySchema.Slice(start: 0, length: i);
Console.WriteLine(string.Concat(left, right));
}
输出:
1234523451
34512
45123
51234
我被要求以最小的内存使用量反转字符数组。
char[] charArray = new char[]{'C','o','w','b','o','y'};
方法:
static void Reverse(ref char[] s)
{
for (int i=0; i < (s.Length-i); i++)
{
char leftMost = s[i];
char rightMost = s[s.Length - i - 1];
s[i] = rightMost;
s[s.Length - i - 1] = leftMost;
}
}
使用模算术怎么样:
public void UsingModularArithmetic()
{
string[] tokens_n = Console.ReadLine().Split(' ');
int n = Convert.ToInt32(tokens_n[0]);
int k = Convert.ToInt32(tokens_n[1]);
int[] a = new int[n];
for(int i = 0; i < n; i++)
{
int newLocation = (i + (n - k)) % n;
a[newLocation] = Convert.ToInt32(Console.ReadLine());
}
foreach (int i in a)
Console.Write("{0} ", i);
}
所以基本上当我从控制台读取时将值添加到数组中。