0
Imがhttps://www.testdome.com/for-developers/solve-question/10282アルゴリズムは、Qから作業
Write a function that, given a list and a target sum, returns zero-based indices of any two distinct elements whose sum is equal to the target sum. If there are no such elements, the function should return null.
For example, FindTwoSum(new List<int>() { 1, 3, 5, 7, 9 }, 12) should return a Tuple<int, int> containing any of the following pairs of indices:
1 and 4 (3 + 9 = 12)
2 and 3 (5 + 7 = 12)
3 and 2 (7 + 5 = 12)
4 and 1 (9 + 3 = 12)
これまでIVました:
class TwoSum
{
public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
{
//throw new NotImplementedException("Waiting to be implemented.");
IList<int> duplicateList = list;
foreach (int i in list)
{
foreach (int j in duplicateList)
{
if (i != j)
{
if (i + j == sum)
{
return Tuple.Create(i, j);
}
}
}
}
return null;
}
public static void Main(string[] args)
{
Tuple<int, int> indices = FindTwoSum(new List<int>() { 1, 3, 5, 7, 9 }, 12);
Console.WriteLine(indices.Item1 + " " + indices.Item2);
}
}
これは私のコードで正しい答えを返しますが、中に4例3を失敗していますquesitong理由:
Example case: Wrong answer
No solution: Correct answer
One solution: Wrong answer
Performance test with a large number of elements: Wrong answer
アイブ氏はヒントを見
Hint 1: Nested for loops can iterate over the list and calculate a sum in O(N^2) time.
Hint 2: A dictionary can be used to store pre-calculated values, this may allow a solution with O(N) complexity.
だから私は辞書を使用する必要がhint2合格するために、ネストされたループが、Imは、このインスタンスで推測を使用してイム...どのように私はこの辞書を使用してにリファクタリングすることができますか? 助けてくれてありがとう!
合計が望ましい合計であるペアを見つけると、すぐに戻ります。一時的なコレクションを作成してペアを追加し、 'foreach'の後でコレクションを返すようにしてください – Vivick
コレクションが注文されている場合、それぞれをすべて一致させるのではなく、内側から検索することができます。 :) – Noctis
あなたの質問は読みにくいです。あなたが何かを引用している場合には、コードセクションを引用符で置き換えることができます。 –