[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].
一刷題解(Brute Force):
這個題給我們一個數組(arr)和一個目標值(target),讓我們找出「唯一」的一對元素的索引,它們的和等於目標值。最簡單粗暴的方式就是直接寫一個嵌套循環進行遍歷。當外層下標為i時,內層循環要搜索的目標就是 target - arr[i]。如果這一次外層循環沒有找到,外層下標+1,內層下標則始終從外層下標 + 1開始遍歷到數組尾部。
public class Solution{
public int[] TwoSum(int[] nums, int target){
int res1 = 0;
int res2 = 0;
for(int i = 0; i < nums.Length; i++)
{
for(int j = i + 1; j < nums.Length; j++)
{
if(nums[j] == target - nums[i]){
res1 = i;
res2 = j;
}
}
}
return int[2]{res1, res2};
}
}
二刷題解(Dictionary):
由於我們已經知道了target必然是由數組裡的兩個元素相加後得出,而這個組合又是唯一的。因此,與其用兩個循環把所有元素的和都檢查一遍,不如只用一個循環加一個保存數組的元素值的字典(Key是值,Value是索引),先把當前元素值與目標值之間的差求出來(target - nums[i]),然後檢查一下字典裡有沒有與這個差相等的值,如果有,那就代表當前的值的索引,還有字典中與(target - nums[i])相等的Key對應的Value就是我們的答案。
public class Solution {
public int[] TwoSum(int[] nums, int target) {
int[] res = new int[2]{-1, -1};
//保存數組被遍歷過的值(Key)及其索引(Value)的字典
Dictionary<int, int> targetDict = new Dictionary<int, int>();
for(int i = 0; i < nums.Length; i++)
{
//求出當前元素與目標之間的差值
int remain = target - nums[i];
//嘗試在字典中找出這個差值
if(targetDict.TryGetValue(remain, out res[0]))
{
res[1] = i;
break;
}
//找不到就把當前值加到字典裡,讓後面的元素檢查
if(!targetDict.ContainsKey(nums[i]))
{
targetDict.Add(nums[i], i);
}
}
return res;
}
}