@@ -29,7 +29,9 @@ The easiest solution to come up with is Brute Force. We could write two for-loop
2929
3030## Code
3131
32- - Support Language: JS
32+ - Support Language: JS,C++,Java,Python
33+
34+ Javascript Code:
3335
3436``` js
3537/**
@@ -49,6 +51,55 @@ const twoSum = function (nums, target) {
4951};
5052```
5153
54+ C++ Code:
55+
56+ ``` cpp
57+ class Solution {
58+ public:
59+ vector<int > twoSum(vector<int >& nums, int target) {
60+ unordered_map<int, int> hashtable;
61+ for (int i = 0; i < nums.size(); ++i) {
62+ auto it = hashtable.find(target - nums[ i] );
63+ if (it != hashtable.end()) {
64+ return {it->second, i};
65+ }
66+ hashtable[ nums[ i]] = i;
67+ }
68+ return {};
69+ }
70+ };
71+ ```
72+
73+ Java Code:
74+
75+ ```java
76+ class Solution {
77+ public int[] twoSum(int[] nums, int target) {
78+ Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
79+ for (int i = 0; i < nums.length; ++i) {
80+ if (hashtable.containsKey(target - nums[i])) {
81+ return new int[]{hashtable.get(target - nums[i]), i};
82+ }
83+ hashtable.put(nums[i], i);
84+ }
85+ return new int[0];
86+ }
87+ }
88+ ```
89+
90+ Python Code:
91+
92+ ``` py
93+ class Solution :
94+ def twoSum (self , nums : List[int ], target : int ) -> List[int ]:
95+ hashtable = dict ()
96+ for i, num in enumerate (nums):
97+ if target - num in hashtable:
98+ return [hashtable[target - num], i]
99+ hashtable[nums[i]] = i
100+ return []
101+ ```
102+
52103** _ Complexity Anlysis_ **
53104
54105- _ Time Complexity_ : O(N)
0 commit comments