C# Int Array Return 等于目标的求和成员的索引

C# Int Array Return Indices of Summed Members Equaling Target

好的,编程新手,Stack 新手。我一直在寻找重复的问题,但它们似乎是针对 python 和 JS.

我即将完成我的第一个 leetcode 练习。我知道我很糟糕,但我在数组上花了将近 4 个小时。

最后一个练习要我接受一个 int[] 和一个 int 目标,返回两个数组成员的索引加起来等于目标。

我放弃了排序,直接把它们整理好。我想把基本的弄下来,然后再添加一个排序。

问题:当我运行下面的代码时,我只得到-1,-1。但是当我设置断点时,我看到变量保存了正确的信息,所以我有点停滞不前,因为我使用了可用的调试工具。

欢迎任何指导或建议,我不是在寻找任何人为我“弄清楚”。如果你想牵着我的鼻子走,我不会生气的。

public class Solution
{
    public int[] TwoSum(int[] nums, int target)
    {

        int low = 0;
        int high = nums.Length - 1;

        while (low < high)
        {
            var sum = nums[low] + nums[high];

            if (sum == target)
            {
                Console.WriteLine("{0}, {1}", Array.IndexOf(nums, low), Array.IndexOf(nums, high));
                break;

            }
            else if (sum < target)
            {
                low++;
            }
            else
            {
                high--;
            }
        }
        Console.ReadKey();
        return null;
    }
}
class Program
{
    static void Main(string[] args)
    {
        int[] nums = { 3, 12, 23, 34, 45 };
        Solution ui = new Solution();
        ui.TwoSum(nums, 15);
    }
} 

看起来您已经在高变量和低变量中有了索引。 Array.IndexOf(nums, low) 正在尝试查找不存在的索引值的索引。 -1 是 return 值,当您要搜索的内容未在数组中找到时。

如果我理解正确,您可以将 Console 行更新为:

Console.WriteLine("{0}, {1}", low, high);

这是解决问题的另一个建议。 我不认为你真的需要为了找到两个总和为特定目标的元素而对东西进行排序。

此外,这在我看来更简单。

using System;

public class Program
{
    public static void Main()
    {
        int[] nums = {3, 23, 12, 34, 45};
        var result = TwoSum(nums, 15);
        if (result.Length == 0)
            Console.WriteLine("no combination did sum up to the target sum");
            
        Console.WriteLine(result[0] + " " + result[1]);
    }

    public static int[] TwoSum(int[] nums, int target)
    {
        for (int outerIndex = 0; outerIndex < nums.Length; outerIndex++)
        {
            for (int innerIndex = 1; innerIndex < nums.Length; innerIndex++) {
                if (nums[outerIndex] + nums[innerIndex] == target)
                    return new int[2]{outerIndex, innerIndex};              
            }
        }
        
        return new int[0]{};
    }
}