https://leetcode.com/problems/two-sum/description/
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].
- 数组简单题,hash表。有三种解法:1、跟冒泡思想一样,挨个做加法比较;2、先做hash,然后扫描一遍数组,用STL find看是否在hash表中能找到余数。这里需要注意如果全部扫描一遍,是可以找到两对重复结果的,所以如果找到结果就返回;3、跟2的思想一样用hash,不过针对2种会出现重复结果的情况,这次直接扫描数组,边扫描数组,边看是否hash表中能找到余数,如果没有则边插入到hash表。
- 注意对map插入值时,不能使用at(k)来访问下标插入,因为k这时候不存在,所以会报错。需要用[k]来代替。
- map::at - C++ Reference
- http://www.cplusplus.com/reference/map/map/at/
- Returns a reference to the mapped value of the element identified with key k.
- If k does not match the key of any element in the container, the function throws an out_of_range exception.
- https://leetcode.com/problems/two-sum/solution/
1 // 2 // main.cpp 3 // LeetCode 4 // 5 // Created by Hao on 2017/3/16. 6 // Copyright © 2017年 Hao. All rights reserved. 7 // 8 9 #include <iostream> 10 #include <vector> 11 #include <unordered_map> 12 using namespace std; 13 14 class Solution { 15 public: 16 // Approach #1 (Brute Force) 17 vector<int> twoSum(vector<int>& nums, int target) { 18 vector<int> vResult; 19 20 for (int i = 0; i < nums.size(); i ++) { 21 for (int j = i + 1; j < nums.size(); j ++) { // j = i + 1 to avoid dup 22 if (target == nums.at(i) + nums.at(j)) { 23 vResult.push_back(i); 24 vResult.push_back(j); 25 } 26 } 27 } 28 29 return vResult; 30 } 31 32 // Approach #2 (Two-pass Hash Table) 33 vector<int> twoSum2(vector<int>& nums, int target) { 34 vector<int> vResult; 35 unordered_map<int, int> hashmap; 36 37 for (int i = 0; i < nums.size(); i ++) { 38 // hashmap.at(nums.at(i)) = i; // terminating with uncaught exception of type std::out_of_range: unordered_map::at: key not found 39 hashmap[nums.at(i)] = i; 40 } 41 42 for (int i = 0; i < nums.size(); i ++) { 43 int complement = target - nums.at(i); 44 45 if (hashmap.find(complement) != hashmap.end() && hashmap.at(complement) != i) { 46 vResult.push_back(i); 47 vResult.push_back(hashmap.at(complement)); 48 49 return vResult; // Need to return here, or else would find dup results (i, hashmap.at(complement)) & (hashmap.at(complement), i) 50 } 51 } 52 53 return vResult; 54 } 55 56 // Approach #3 (One-pass Hash Table) 57 vector<int> twoSum3(vector<int>& nums, int target) { 58 vector<int> vResult; 59 unordered_map<int, int> hashmap; 60 61 for (int i = 0; i < nums.size(); i ++) { 62 int complement = target - nums.at(i); 63 64 if (hashmap.find(complement) != hashmap.end() && hashmap.at(complement) != i) { 65 vResult.push_back(i); 66 vResult.push_back(hashmap.at(complement)); 67 } 68 69 hashmap[nums.at(i)] = i; 70 } 71 72 return vResult; 73 } 74 }; 75 76 int main(int argc, char* argv[]) 77 { 78 Solution testSolution; 79 string result; 80 81 vector<int> iVec = {2, 7, 11, 15}; 82 vector<int> vResult; 83 84 /* 85 0 1 86 0 1 87 1 0 88 */ 89 vResult = testSolution.twoSum(iVec, 9); 90 91 for (auto iter : vResult) 92 cout << iter << " "; 93 cout << endl; 94 95 vResult.clear(); 96 97 vResult = testSolution.twoSum2(iVec, 9); 98 99 for (auto iter : vResult) 100 cout << iter << " "; 101 cout << endl; 102 103 vResult.clear(); 104 105 vResult = testSolution.twoSum3(iVec, 9); 106 107 for (auto iter : vResult) 108 cout << iter << " "; 109 cout << endl; 110 111 return 0; 112 }
- Python3 Solution
- Built-in Types — Python 3.7.2 documentation - get(key[, default])
- https://docs.python.org/3/library/stdtypes.html?highlight=get#dict.get
- Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to
None
, so that this method never raises aKeyError
.
Built-in Functions — Python 3.7.2 documentation - enumerate(iterable, start=0)
- https://docs.python.org/3/library/functions.html?highlight=enumerate#enumerate
- Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The
__next__()
method of the iterator returned byenumerate()
returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.
1 class Solution: 2 def twoSum(self, nums: List[int], target: int) -> List[int]: 3 dict = {} 4 5 for id, num in enumerate( nums ): 6 if dict.get( target - num ) is not None: 7 return [ id, dict[ target - num ] ] 8 else: 9 dict[ num ] = id