1. 程式人生 > 其它 >LeetCode從讀題到自閉:1. 兩數之和

LeetCode從讀題到自閉:1. 兩數之和

中文題目:

給定一個整數陣列 nums 和一個整數目標值 target,請你在該陣列中找出 和為目標值 的那 兩個 整數,並返回它們的陣列下標。

你可以假設每種輸入只會對應一個答案。但是,陣列中同一個元素不能使用兩遍。

你可以按任意順序返回答案。

示例 1:

輸入:nums = [2,7,11,15], target = 9
輸出:[0,1]
解釋:因為 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:

輸入:nums = [3,2,4], target = 6
輸出:[1,2]
示例 3:

輸入:nums = [3,3], target = 6
輸出:[0,1]

提示:

2 <= nums.length <= 10^3
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10^9
只會存在一個有效答案

英文題目:

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]
Output: 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]

Constraints:

2 <= nums.length <= 10^3
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10 ^9
Only one valid answer exists.

解法1:暴力列舉

最容易想到的方法是列舉陣列中的每一個數 x,尋找陣列中是否存在 target - x。

當我們使用遍歷整個陣列的方式尋找 target - x 時,需要注意到每一個位於 x 之前的元素都已經和 x 匹配過,因此不需要再進行匹配。而每一個元素不能被使用兩次,所以我們只需要在 x 後面的元素中尋找 target - x。

Demo:

 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         for (int i = 0; i < nums.length - 1; i++) {
 4             for (int j = i + 1; j < nums.length; j++) {
 5                 if (nums[j] == target - nums[i]) {
 6                     return new int[] { i, j };
 7                 }
 8             }
 9         }
10         return null;
11     }
12 }

解法2:雜湊表

遍歷陣列 nums,i 為當前下標,每個值都判斷hashtable中是否存在 target-nums[i] 的 key 值;
如果存在則找到了兩個值,如果不存在則將當前的 (nums[i],i) 存入 hashtable 中,繼續遍歷直到找到為止。

輸入:nums = [2,7,11,15], target = 22
輸出:[0,1]

i=0,22-2=20不在hashtable中,[2,0]存進去;【2,0】
i=1,22-7=15不在hashtable中,[7,1]存進去;【2,0】【7,1】
i=2,22-11=11,不在hashtable中,[11,2]存進去;【2,0】【7,1】【11,2】
i=3,22-15=7,存在【7,1】

輸出[1,3]

 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
 4         for (int i = 0; i < nums.length; ++i) {
 5             if (hashtable.containsKey(target - nums[i])) {
 6                 return new int[]{hashtable.get(target - nums[i]), i};
 7             }
 8             hashtable.put(nums[i], i);
 9         }
10         return new int[0];
11     }
12 }

附:

型別佔用儲存空間表數範圍
byte 1位元組=8bit位 -128 ~ 127
short 2位元組 -2^{15} ~2 ^{15}-1
int 4位元組 -2^{31} ~ 2 ^{31}-1 (約21億)
long 8位元組 -2^{63} ~ 2 ^{63}-1