### LeetCode: 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].


1.暴力破解: 兩個迴圈遍例相加，解法要算N(N-1)/2次，O(N²)的時間複雜度。


public class Solution {
public int[] TwoSum(int[] nums, int target) {
for (int i = 0; i < nums.Length; i++)
{
for (int j = i + 1; j < nums.Length; j++)
{
if (nums[i] + nums[j] == target)
{
return new int[] { i, j };
}
}
}
return nums;
}
}


2.使用Dictionary紀錄已比較過的item:


public class Solution {
public int[] TwoSum(int[] nums, int target) {
Dictionary<int, int> dic = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++)
{
var diff = target - nums[i];
if (dic.ContainsKey(diff))
{
return new int[] { dic[diff], i };
} else
{
if (!dic.ContainsKey(nums[i])) {
dic.Add(nums[i], i);
}
}
}
return nums;
}
}


Ref:

https://medium.com/@desolution/%E5%BE%9Eleetcode%E5%AD%B8%E6%BC%94%E7%AE%97%E6%B3%95-1-400da76b51b4

https://leetcode.com/articles/two-sum/