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:

找尋Dictionary中是否有存在target減去nums中所遍歷的item差值,如果有即回傳,沒有則將item的值與index存入Dictionary。

優點為每個item數值只會被比較過一次,最壞的狀況為遍歷整個array後,就可以得到答案,由於Dictionary的ContainsKey與Add皆為O(1),所以最糟的情況下遍歷整個Dictionary需要O(N)。


 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/