File tree Expand file tree Collapse file tree 2 files changed +58
-0
lines changed Expand file tree Collapse file tree 2 files changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ C++
2
+
3
+ 1 ) Brute Force
4
+ class Solution {
5
+ public:
6
+ vector<int > twoSum(vector<int >& nums, int target) {
7
+ vector<int > ret;
8
+ int size = nums.size();
9
+ for(int i=0 ; i < size - 1 ;i++)
10
+ {
11
+ for(int j = i+1 ; j<size ; j++)
12
+ {
13
+ if(nums[ i] +nums[ j] == target)
14
+ {
15
+ ret.push_back(i);
16
+ ret.push_back(j);
17
+ return ret;
18
+ }
19
+ }
20
+ }
21
+ return ret;
22
+ }
23
+ }; //O(n^2)
24
+
25
+ 2 ) Hash Table
26
+ class Solution {
27
+ public:
28
+ vector<int > twoSum(vector<int >& nums, int target) {
29
+ vector<int > ret;
30
+ int size = nums.size();
31
+ int diff;
32
+ unordered_map<int,int>m;
33
+ for (int i=0 ; i<size ; i++)
34
+ {
35
+ diff = target - nums[ i] ;
36
+ if(m.find(diff) != m.end() && m.find(diff) -> second != i )
37
+ {
38
+ ret.push_back(i);
39
+ ret.push_back(m.find(diff) -> second);
40
+ return ret;
41
+ }
42
+ m[ nums[ i]] = i;
43
+ }
44
+ return ret;
45
+ }
46
+ }; //O(n)
Original file line number Diff line number Diff line change
1
+ Python
2
+
3
+ 1 ) Brute force
4
+ class Solution(object):
5
+ def twoSum(self, nums, target):
6
+ #Using Two pointers P1 and P2 to represent every possible pairs of the array.
7
+ for p1 in range(len(nums)):
8
+ for p2 in range(p1+1, len(nums)):
9
+ #If one of those pairs add together equal to the target return the answer else return None.
10
+ if nums[ p1] + nums[ p2] == target:
11
+ return [ p1, p2]
12
+ return 'None'
You can’t perform that action at this time.
0 commit comments