Skip to content

Commit 2d4e5c8

Browse files
committed
2some👄
1 parent caac289 commit 2d4e5c8

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

Striver Sheet/Day-4/Two Sum.cpp

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
Two Sum
3+
=======
4+
5+
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
6+
7+
You may assume that each input would have exactly one solution, and you may not use the same element twice.
8+
9+
You can return the answer in any order.
10+
11+
Example 1:
12+
Input: nums = [2,7,11,15], target = 9
13+
Output: [0,1]
14+
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
15+
16+
Example 2:
17+
Input: nums = [3,2,4], target = 6
18+
Output: [1,2]
19+
20+
Example 3:
21+
Input: nums = [3,3], target = 6
22+
Output: [0,1]
23+
24+
Constraints:
25+
2 <= nums.length <= 103
26+
-109 <= nums[i] <= 109
27+
-109 <= target <= 109
28+
Only one valid answer exists.
29+
*/
30+
31+
class Solution
32+
{
33+
public:
34+
vector<int> twoSum(vector<int> &nums, int target)
35+
{
36+
unordered_map<int, int> prev;
37+
for (int i = 0; i < nums.size(); ++i)
38+
{
39+
int tar = target - nums[i];
40+
if (prev.find(tar) != prev.end())
41+
return {prev[tar], i};
42+
else
43+
prev[nums[i]] = i;
44+
}
45+
return {-1, -1};
46+
}
47+
};

Striver Sheet/README.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,12 @@
3131

3232
###
3333

34-
- []() - [Cpp Soultion](./Day-/.cpp)
34+
- [Two Sum](https://leetcode.com/problems/two-sum/) - [Cpp Soultion](./Day-4/Two%20Sum.cpp)
35+
- []() - [Cpp Soultion](./Day-4/.cpp)
36+
- []() - [Cpp Soultion](./Day-4/.cpp)
37+
- []() - [Cpp Soultion](./Day-4/.cpp)
38+
- []() - [Cpp Soultion](./Day-4/.cpp)
39+
- []() - [Cpp Soultion](./Day-4/.cpp)
3540

3641
###
3742

0 commit comments

Comments
 (0)