[LeetCode | C++] August LeetCoding Challenge 2021 — Week1 Two Sum (2nd, August)

yeahsilver
1 min readAug 5, 2021

--

📃 Problem

https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/613/week-1-august-1st-august-7th/3836/

💡 Check Point

  • Consider how to get the index of a given value in vector “nums”

👩‍💻 My Solution

  1. First Approach — Implementation
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;

for(int i = 0 ; i <nums.size(); i++) {
for(int j = i+1; j < nums.size(); j++) {
if(i == j) continue;

if(nums[i]+nums[j] == target) {
result.push_back(i);
result.push_back(j);

break;
}
}
}

return result;
}
};

2. Second Approach — Using “find” method of vector

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;

for(int i = 0; i < nums.size(); i++) {
int value = target-nums[i];
auto it = find(nums.begin()+i+1, nums.end(), value);
if(it == nums.end()) {
continue;
} else {
result.push_back(i);
result.push_back(it-nums.begin());
break;
}
}

return result;
}
};

3. Third Approach — Using hash table (unordered map)

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;

unordered_map<int, int> hash_table;

for(int i = 0; i < nums.size(); i++) {
int find = target-nums[i];
if(hash_table.find(find) != hash_table.end()) {
result.push_back(hash_table[find]);
result.push_back(i);
return result;
}
hash_table[nums[i]] = i;
}

return result;
}
};

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response