In this article we will learn about LeetCode First question Two Sum in detail with optimized solution with Example.
Table of Contents
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[] {i, j};
}
}
}
return new int[] {};
}
}
// 2023
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1; j < nums.size(); j++) {
if (nums[i] + nums[j] == target) {
return {i, j};
}
}
}
return {};
}
};
// 2023
import java.util.HashMap;
import java.util.Map;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numToIndex = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (numToIndex.containsKey(target - nums[i])) {
return new int[] {numToIndex.get(target - nums[i]), i};
}
numToIndex.put(nums[i], i);
}
return new int[] {};
}
}
#include <unordered_map>
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> mp;
for(int i = 0; i < nums.size(); i++){
if(mp.find(target - nums[i]) == mp.end())
mp[nums[i]] = i;
else
return {mp[target - nums[i]], i};
}
return {-1, -1};
}
};
Time complexity: O(N);
Space Complexity: O(N);
I hope you like this Amazing Two Sum article.🙂
Also Read :
Blockchain is a shared, immutable ledger that facilitates the process of recording transactions and tracking assets…
In this article we will learn about LeetCode Third question Longest Substring Without Repeating Characters in detail…
In this article we will learn about LeetCode Second question Add Two Numbers in detail with optimized…
In this amazing Web Designing Roadmap 2023 article, we’ll learn about A to Z about…
Android developer -- In this amazing Android Developer Roadmap article, we’ll learn about A to…
The roadmap for a full stack developer can vary depending on the individual's goals and…