---
tags: LeetCode
---
# 1. Two Sum
Given an array of integers, return **indices** of the two numbers such that they add up to a specific target.
You may assume that each input **would have exactly one solution**, and you may not use the same element twice.
- Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
輸入範本如下
```C#
public class Solution {
public int[] TwoSum(int[] nums, int target) {
}
}
```
---
### 直覺想法
- 因為題目限制只有一個解 , 所以不會有超過一個解答以及無解的情況發生.
- 怎麼再走訪的時候 , 有辦法拿到之前走過的成員 , 因為要判斷 a + b = target.
- nums 似乎沒有什麼可以用的特徵 , 所以似乎只能使用 Dictionary 來儲存走訪過的結果 (target - num )
- 走訪 nums , 若現在走訪的數字存在於 Dictionary 中
- 現在走訪的數字 = target - 上次走訪的數字
- 現在走訪的數字 + 上次走訪的數字 = target
```C#
public int[] TwoSum(int[] nums, int target)
{
// key is num , and value is index
Dictionary<int, int> keyValuePairs = new Dictionary<int, int>();
for (int index = 0; index < nums.Length; index++)
{
var num = nums[index];
if (keyValuePairs.ContainsKey(num))
{
return new int[] { keyValuePairs[num], index };
}
// 將 index 指派給該 key 的值 , 若無 key 則新建一個 key
keyValuePairs[target - num] = index;
}
throw new Exception();
}
```
### Thank you!
You can find me on
- [GitHub](https://github.com/s0920832252)
- [Facebook](https://www.facebook.com/fourtune.chen)
若有謬誤 , 煩請告知 , 新手發帖請多包涵
# :100: :muscle: :tada: :sheep: