繁体   English   中英

C# 定位数组中的值并将其右移

[英]C# locate value in a array and move it to right

我的任务是在数组中找到与给定值相同的元素,然后将其向右移动,同时保持其他元素的顺序。 一个例子(测试用例):

{1, 2, 0, 1, 0, 1, 0, 3, 0, 1} for value = 0 => {1, 2, 1, 1, 3, 1, 0, 0, 0, 0}

虽然我的代码可以做上面的例子,但它不能做的是一个非常特殊的情况:如果数组中的元素等于值并且下一个元素也等于值,它不会移动元素。 再举个例子:

{ 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;

        }

现在这个

我有一个简单的方法来解决这个问题。 运行一个循环,你继续计算不等于你的数字的数字。 并继续分配给arr[count] 然后增加count 最后,您将需要用给定的数字分配所有剩余的数字。

static void MoveToEnd(int []arr, int n)
{
    int count = 0; 

    for (int i = 0; i < arr.Length; i++)
        if (arr[i] != n)
            arr[count++] = arr[i]; 

    while (count < arr.Length)
        arr[count++] = n;
}

请注意,我是通过电话输入此答案的,因此请避免输入错误。

这是一个错误的经典。 这样想:

假设您要将所有 0 移到后面 ( value = 0 )。 当你在 position 处找到一个零时,比方说 source[2],你将你的数组从这个:

      1 1 0 0 1 1    
source[2] ^

对此:

      1 1 0 1 1 0
source[2] ^

现在您已经移动了数组,代码中的下一步是将 i 增加 1。这意味着您进行的下一次比较将与 source[3] 进行。 在上面的数组中,它看起来像这样:

      1 1 0 1 1 0
  source[3] ^

你看到问题了吗? 如果没有,请告诉我,我可以进一步解释。

附言。 发布的其他代码存在一些问题,如果您要将其上交作业,可能会阻止您获得满分:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM