【发布时间】:2021-11-23 22:19:50
【问题描述】:
我的任务是在数组中找到一个与给定值相同的元素,然后在保持其他元素顺序的同时将其向右移动。一个例子(测试用例):
{1, 2, 0, 1, 0, 1, 0, 3, 0, 1} for value = 0 => {1, 2, 1, 1, 3, 1, 0, 0, 0, 0}
虽然我的代码可以在上面的例子中做到这一点,但它不能做的是一个非常具体的情况:如果数组中的元素等于 value 并且下一个元素也等于 value,它不会移动元素。再举个例子:
{ 1, int.MinValue, int.MinValue, int.MaxValue, int.MinValue, -1, -3, -9, 1 }, value = int.MinValue
预期结果:{ 1, int.MaxValue, -1, -3, -9, 1, int.MinValue, int.MinValue, int.MinValue }
我的代码结果:{ 1, int.MinValue ,int.MaxValue, -1, -3, -9, 1, int.MinValue, int.MinValue }
我认为转移是唯一的解决方案,是吗?我遇到了很多问题,我也尝试过Array.Copy,但结果总是超出范围。
我怎样才能让它在所有情况下都能正确移动/旋转?
代码:
static void Main(string[] args)
{
int[] source = new int[] { 1, int.MinValue, int.MinValue, int.MaxValue, int.MinValue, -1, -3, -9, 1 };
int value = int.MinValue;
for (int i = 0; i < source.Length; i++)
{
if (source[i] == value)
{
LeftShiftArray(source, i);
}
}
for (int i = 0; i < source.Length; i++)
{
Console.WriteLine(source[i]);
}
}
public static void LeftShiftArray(int[] source, int i)
{
var temp1 = source[i];
for (var j = i; j < source.Length - 1; j++)
{
source[j] = source[j + 1];
}
source[source.Length - 1] = temp1;
}
现在这个
【问题讨论】:
标签: c# arrays search rotation bit-shift