In this Leetcode Two sum problem solution, we have Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Problem solution in Python.
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: x = len(nums) for i in range(x-1): for j in range(1,x): if i == j: continue if nums[i] + nums[j] == target: return [i,j]
Problem solution in Java.
class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer,Integer> map = new HashMap<>(); int noToFind = 0; for(int i = 0; i < nums.length; i++) { if(map.containsKey(nums[i])) { int[] arr = {map.get(nums[i]), i}; return arr; } noToFind = target - nums[i]; map.put(noToFind, i); } return null; } }
Problem solution in C++.
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { int n,i,j,ind,ind2; n=nums.size(); vector<int> ans; unordered_map<int, int> mp; for (int i = 0; i < n; i++) { if (mp.find(target - nums[i]) != mp.end()) { ans.push_back(mp[target - nums[i]]); ans.push_back(i); return ans; } mp[nums[i]] = i; } return ans; } };
Problem solution in C.
int* twoSum(int* nums, int numsSize, int target, int* returnSize){ *returnSize=2; int *arr=(int *)malloc((*returnSize)*sizeof(int)); for(int i=0;i<numsSize;i++){ for(int j=i+1;j<numsSize;j++){ if(nums[i]+nums[j]==target){ arr[0]=i; arr[1]=j; break; } } } return arr; }
Pretty sure there is a better way to do the two sum in C with a hash map