Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
public class Solution {
public int[] TwoSum(int[] nums, int target) {
Dictionary<int, int> temp = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++)
{
int left = target - nums[i]; //目前數字的餘數
if (temp.ContainsKey(left))
return new int[] { temp[left], i }; //找到了,直接回傳Index
if (!temp.ContainsKey(nums[i]))
temp.Add(nums[i], i); //沒有找到,把找過的存起來,可以當作另一個數字的餘數
}
return null;
}
}
最近手邊專案到一段落,趁著空檔鍛鍊一下自己的思考邏輯,也把C#各種資料結構、工具更加熟悉,並記錄解題過程。
利用餘數,尋訪每個數字,並使用Dictionary的Key/Value把出現過的數字存在Dictionary,重點是將數字存在Dictionary.Key,數字的index存在Dictionary.Value,再利用Dictionary.ContainsKey找到相對應的餘數,並回傳Dictionary.Value(Index)。
參考:透過 LeetCode 解救美少女工程師的演算法人生系列 第 3 篇