1. 程式人生 > >LeetCode—1—Two Sum(雜湊表的使用)

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].

翻譯

給定一個整數陣列,找出其中兩個數滿足相加等於你指定的目標數字。
每個輸入只有一個唯一解。相同的元素不能用兩次。

解題思路

那麼本題呢雙重迴圈的方法在這裡就不說了。主要展示一下藉助HashMap實現。以及要考慮的問題。
思路還是比較簡單的。首先我們把所有元素放到map中。key為元素本身。value為元素在陣列中的索引值。放到map中是因為方便查詢元素的位置。同時雜湊表查詢元素的時間複雜度是O(1)級別的。
然後再遍歷一邊陣列。查詢map中對應的那個元素。
程式碼如下

// 1. Two Sum
// https://leetcode.com/problems/two-sum/description/
// 時間複雜度:O(n) // 空間複雜度:O(n) public class Solution2 { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> record = new HashMap<Integer, Integer>(); for(int i = 0 ; i < nums.length ; i ++) record.put(nums[i], i); for(int i = 0 ; i <
nums.length; i ++){ if(record.containsKey(target - nums[i])) if(record.get(target - nums[i]) != i){ //不能是同一個的元素相加等於目標值 int[] res = {i, record.get(target - nums[i])}; return res; } } throw new IllegalStateException("the input has no solution"); } }

題到這裡就結束了嗎?那麼有沒有想過這麼一種可能。這個陣列中假如有兩個值都為a的元素。那麼我們將陣列中的元素放到map中時。後面的那個a就將前面那個a覆蓋了。a對應的value值為後面那個a的索引。如圖:

如果此題的目標值剛好是2a。就是這兩個a相加呢?其實這種情況也沒有關係。想想當我們第二次遍歷陣列時。首先肯定遍歷到的是陣列中的第一個a。此時我們查詢map時。找到的另一個值也是a。而map中的這個a剛好使我們陣列中的第二個a。因為map中第一個a已被第二個覆蓋掉了。所以取當前陣列中的a的索引。同時取map中a的索引。就剛好是我們要的答案。
關注我免費下載CSDN

關注公眾號哦