列表说我有一个列表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准备就绪),并且不会受到性能的影响(合理的性能)
感谢。
答案 0 :(得分:64)
最简单的方式(对于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>
,那会更简单:
int first = linkedList.First;
linkedList.RemoveFirst();
linkedList.AddLast(first);
这是O(1),因为每个操作都是恒定时间。
cadrell0使用队列的解决方案是单个语句,因为Dequeue
删除元素并且返回它:
queue.Enqueue(queue.Dequeue());
虽然我找不到任何关于此性能特征的文档,但我希望期望 Queue<T>
使用数组和索引作为“虚拟起点”来实现 - 在这种情况下,这是另一个O(1)解决方案。
请注意,在所有这些情况下,您都要先检查列表是否为空。 (你可能认为这是一个错误,或者是一个无操作。)
答案 1 :(得分:45)
您可以将其实现为队列。将相同的值排队并排队。
**我不确定将List转换为队列的表现,但是人们对我的评论提出了支持,所以我将其作为答案发布。
答案 2 :(得分:20)
我用这个:
public static List<T> Rotate<T>(this List<T> list, int offset)
{
return list.Skip(offset).Concat(list.Take(offset)).ToList();
}
答案 3 :(得分:8)
似乎有些回答者认为这是探索数据结构的机会。虽然这些答案内容丰富且有用,但它们并不是非常Linq'ish。
Linq'ish的方法是:你得到一个扩展方法,它返回一个知道如何构建你想要的懒惰的IEnumerable。此方法不会修改源,只应在必要时分配源的副本。
public static IEnumerable<IEnumerable<T>> Rotate<T>(this List<T> source)
{
for(int i = 0; i < source.Length; 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.Length; 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
}
答案 4 :(得分:3)
这个怎么样:
var output = input.Skip(rot)
.Take(input.Count - rot)
.Concat(input.Take(rot))
.ToList();
其中rot
是要旋转的点数 - 必须小于input
列表中的元素数。
正如@ cadrell0回答所示,如果您对列表进行了全部操作,则应使用队列而不是列表。
答案 5 :(得分:2)
我的解决方案可能太基本了(我不想说它很蹩脚......)而不是LINQ'ish。
但是,它有相当不错的表现。
List<List<HashMap<String, String>>> routes
答案 6 :(得分:1)
尝试
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]);
虽然,我更喜欢Jon Skeet的答案。
答案 7 :(得分:1)
你可以在.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()
。
答案 8 :(得分:1)
我的阵列解决方案:
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);
}
答案 9 :(得分:1)
您可以使用以下代码进行左旋转。
List<int> backUpArray = array.ToList();
for (int i = 0; i < array.Length; i++)
{
int newLocation = (i + (array.Length - rotationNumber)) % n;
array[newLocation] = backUpArray[i];
}
答案 10 :(得分:0)
我已经使用了以下扩展名:
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
}
答案 11 :(得分:0)
下面是我的方法。谢谢
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;
}
答案 12 :(得分:0)
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;
}
答案 13 :(得分:0)
使用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();
}
答案 14 :(得分:-1)
我被要求以最少的内存使用量来反转字符数组。
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;
}
}
答案 15 :(得分:-1)
如何使用模运算:
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);
}
因此,当我从控制台读取时,基本上将值添加到数组中。