Skip to content

Commit 8a74f49

Browse files
add c++ solution for 1
1 parent b6c00b2 commit 8a74f49

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -764,7 +764,7 @@ Your ideas/fixes/algorithms are more than welcome!
764764
|4|[Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_4.java) | ? | ? | |Hard | Divide and Conquer
765765
|3|[Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_3.java) | O(n) | O(k) | |Medium | HashMap, Sliding Window
766766
|2|[Add Two Numbers](https://leetcode.com/problems/add-two-numbers/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_2.java) | O(max(m,n)) | O(1) | |Medium | LinkedList
767-
|1|[Two Sum](https://leetcode.com/problems/two-sum/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_1.java)| O(n)| O(n) |[:tv:](https://www.youtube.com/watch?v=kPXOr6pW8KM&t=)|Easy| HashMap
767+
|1|[Two Sum](https://leetcode.com/problems/two-sum/)|[Java](../master/src/main/java/com/fishercoder/solutions/_1.java), [C++](../master/cpp/_1.cpp)| O(n)| O(n) |[:tv:](https://www.youtube.com/watch?v=kPXOr6pW8KM&t=)|Easy| HashMap
768768

769769
## Database
770770

cpp/_1.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
1. Two Sum
3+
4+
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
5+
6+
You may assume that each input would have exactly one solution, and you may not use the same element twice.
7+
8+
Example:
9+
10+
Given nums = [2, 7, 11, 15], target = 9,
11+
12+
Because nums[0] + nums[1] = 2 + 7 = 9,
13+
return [0, 1].
14+
15+
*/
16+
class Solution {
17+
public:
18+
vector<int> twoSum(vector<int>& nums, int target) {
19+
unordered_map<int, int> m;
20+
vector<int> result;
21+
for(int i=0; i<nums.size(); i++){
22+
// not found the second one
23+
if (m.find(nums[i])==m.end() ) {
24+
// store the first one poisition into the second one's key
25+
m[target - nums[i]] = i;
26+
}else {
27+
// found the second one
28+
result.push_back(m[nums[i]]);
29+
result.push_back(i);
30+
break;
31+
}
32+
}
33+
return result;
34+
}
35+
};

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy