有趣的一个循环数组问题

问题:假设有12个数字,1-12,每隔4个取出一个,到最后一位的时候则从第一位继续,知道不足四位,问取出的最后一位数字是多少?

乍一看,好像不难,然后我尝试着写,发现数组的序列index不好取,没辙,只好问问大神们,下面附上大神给出的代码

Queue<int> list = new Queue<int>(new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 });
int index = 1;
while (list.Count >= 4)
{
int nowInt = list.Dequeue();
if (index % 4 != 0)
list.Enqueue(nowInt);
else Console.WriteLine(nowInt);
index++;
}

大蛇用了队列实现,于是我想,直接用list站队是不是也可以?

List<int> arr = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
List<int> deleteArr = new List<int>();
int startIndex = 1;
while (arr.Count >= 4)
{
int currentInt = arr[0];
if (startIndex % 4 != 0)
{
arr.RemoveAt(0);
arr.Add(currentInt);
}
else
{
arr.RemoveAt(0);
deleteArr.Add(currentInt);
}
startIndex++;
}
foreach (var item in deleteArr)
{
Console.WriteLine(item);
}

得出的结果也是一样的,但是回过来想想这个题,我总是想着直接取4,8,12,,,位,却发现在末尾之后再连接第一位时,index就不好处理了,哎!!!还是菜,有木有大蛇有更好的方法?

猜你喜欢

转载自www.cnblogs.com/JueYingHuang/p/10142703.html