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
本系列文之後也会置於个人网站 其实我原本是想要 RESTer 干到底的哈?。 今天有一点是插话的。...
那今天呢,我们来讲解一下请LIR注册ASN需要几个重要的Object 首先,我们这边是以RIPE为例...
创世神创造了世界,还觉得不够,又做了一颗月球。 过了两天觉得地球不够圆,决定把存在月球的 pi拿回来...
大家好~ 接着一起来介接 API 吧! 今天先从 Google Calendar API 开始~ 上...
目前的版面配置是基本的瀑布流效果,而此模式较着重在显示书本封面图片,一列只能出现三本书单,RWD 的...