Two Sum是LeetCode基礎的演算法~
例如~ 有一個array放 7, 11, 5, 2~ 然後~target是9~
最後它的輸出會是 0,3~
學習目標: Two sum的概念及實務
學習難度: ☆☆☆
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class MainProgram
{
static int[] Twosum(int[] numbers, int target)
{
//用Dictionary實作
Dictionary<int, int> dictionary = new Dictionary<int, int>();
for (int i = 0; i < numbers.Length; i++)
{
int temp = target - numbers[i];
if (dictionary.ContainsKey(temp))
{
//dictionary[temp]是key(數值),會回傳value(索引)
return new int[] { dictionary[temp], i };
}
else
{
// 因為我們要求索引,所以這裡的value是i
dictionary[numbers[i]] = i;
}
}
return null;
}
static void Main()
{
int[] arrays = new int[] { 7, 11, 5, 2 };
int target = 9;
Twosum(arrays, target);
}
}
}
參考資料:
https://ithelp.ithome.com.tw/articles/10217042