【问题标题】:Understanding why my code for the Two Sum (LeetCode problem) in C# does not work for expected answer of [1,2]了解为什么我的 C# 中的二和(LeetCode 问题)代码不适用于 [1,2] 的预期答案
【发布时间】:2022-01-23 23:28:06
【问题描述】:

我正在尝试解决 LeetCode 的二和问题。在这个问题中,给定一个名为 nums 的整数数组和一个包含名为 target 的整数的变量。问题是要求返回一个数组,其中包含两个数字的索引,这些数字加起来就是目标。

例如,您有 nums = [2,7,11,15] 和 target= 9。预期输出将是 [0,1],因为 2+7 = 9。

我的代码(如下所示)适用于上面的示例,但是,它不适用于 LeetCode 检查的第二个示例:nums= [3,2,4], target = [6], expected 结果是 [1,2]

我想知道为什么我的代码不适用于第二个示例,以及如何修改它以使其正常工作。

我用于此问题的代码:

public class Solution {
    public int[] TwoSum(int[] nums, int target) {
        //Initializing i, k and sum variables
        int i=0;
        int k= 0;
        int sum= 0;
        
        for(i=0; i<= nums.Length-1 ; i++) 
        {
            

            if(i< nums.Length)
            {
                k= i+1;
            
                sum= nums[i] + nums[k];
                
                if(sum== target)
                {
                    //Returns an array in the compiler containing the values of i and k.
                    return new int[] {i, k};
                } else 
                {
                    return new int[0];
                }
                
                
            } else
            {
                return Array.Empty < int > ();
            }           

        }
        return new int[0]; //Returns an empty array if the solution is not found
    }
}

提前谢谢你!

【问题讨论】:

  • 你在调试器中单步调试过代码吗?
  • 另外,请解释一下“不起作用”是什么意思。它会返回不正确的结果吗?抛出异常?
  • 正如 madreflection 所提到的,理解的第一步是使用调试器逐步完成。如果您在 VS Studio 中编写,请设置一个断点,然后查看步骤按钮以在代码执行时浏览代码。乍一看,您的代码似乎在第一次执行 for 循环时立即返回(您有 return 语句,贯穿始终,因此它永远不会进入循环的下一次迭代)。它第一次工作的原因是因为解决方案恰好在第一次迭代中。
  • 从循环中返回空数组的两个地方看起来很可疑。它们禁止您的代码搜索更多解决方案。
  • 我觉得 LeetCode 中的编译器让我很困惑。我知道我需要做 LeetCode 题来练习,但我觉得在 Visual Studio 上做题比使用他们的编译器更容易。

标签: c#


【解决方案1】:

你的问题是这里的 else 块

        if(sum== target)
        {
            //Returns an array in the compiler containing the values of i and k.
            return new int[] {i, k};
        } else 
        {
            return new int[0];
        }

当您没有使用索引 0 和 1 命中目标时,您会返回空数组,而不是尝试使用索引 1 和 2。

如果您删除 else 块,您的代码将适用于您给出的示例。

【讨论】:

  • 非常感谢您,汉斯·基利安!我删除了 Else 块,它可以工作。
【解决方案2】:

你的问题是 else 块有一个 return 所以你的循环不会工作。

但你可以使用:


// bit more array items to test
var nums = new[] { 2, 7, 11, 0, 15, 2, 9 };
int target = 9;

// Your second test case
// var nums = new[] { 3, 2, 4 };
// int target = 6;

var results = new Dictionary<int, int>();
for (var i = 0; i < nums.Length; i++)
{
    var currI = nums[i];
    for (var x = 0; x < nums.Length; x++)
    {
        var currX = nums[x];
        var sum = currI + currX;

        // just with the correct sum and it is not already in the result
        if (sum == target && i != x && !results.ContainsKey(x))
        {
            results[i] = x;
        }
    }
}

这将导致

0, 1
1, 5
3, 6

如果您只需要知道第一个组合,请发送.FirstOrDefault()

可以在这里找到完整的工作示例:dotnetfiddle

【讨论】:

  • 谢谢你,马丁!我删除了 Else 块。我的代码只得到第一个答案,但我会尝试更改它,以便它可以显示其他结果。
【解决方案3】:

你可以简化你的代码:

using System;

public class Program
{
    public static void Main()
    {
        var nums = new[] { 2, 7, 11, 0, 15, 2, 9 };
        int target = 9;

        for (var i = 0; i < nums.Length; i++)
            for (var x = i; x < nums.Length; x++)
                if (nums[i] + nums[x] == target)
                    Console.WriteLine($"{i}, {x}");

    }
}

【讨论】:

  • 谢谢,杰克!是否更喜欢像这样嵌套两个 For 循环,而不是在 If 语句中使用 k= i+1 ?
  • @Evangeline Drink:如果工作正常,没有更好或更坏的方法。我能做的唯一考虑是:测试越少,代码越快。当代码反映在这种情况下称为简单组合的算法时,代码很有趣。不是最后一次使用尽可能少的内存。
  • @Evangeline Drink:您的程序还需要 2 个嵌套的 for 循环,否则,正如现在编写的那样,您将始终只检查一个值,只检查下一个值,而不是所有其他值。
  • 再次感谢!我查找了简单组合算法,这对于为什么可以使用两个 For 循环来解决这个问题是有道理的。
猜你喜欢
  • 2020-04-27
  • 2019-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2020-11-13
相关资源
最近更新 更多