1. Two Sum
Problem
Tags: Array
, Hash Table
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.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 10^4
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10^9
- Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n^2)
time complexity?
Code
C
// 1. Two Sum (5/15/53896)
// Runtime: 72 ms (78.49%) Memory: 6.56 MB (21.30%)
int* twoSum(int* nums, int nums_size, int target, int* return_size) {
int* result = (int*)malloc(sizeof(int) * 2);
int i, j;
for (i = 0; i < nums_size; i++) {
for (j = i + 1; j < nums_size; j++) {
if (nums[i] + nums[j] == target) {
result[0] = i;
result[1] = j;
*return_size = 2;
return result;
}
}
}
return result;
}
GO
// 1. Two Sum (5/22/53846)
// Runtime: 4 ms (88.21%) Memory: 4.34 MB (15.47%)
func twoSum(nums []int, target int) []int {
table := make(map[int]int)
for i := 0; i < len(nums); i++ {
if val, exists := table[nums[i]]; exists {
return []int{val, i}
break
}
table[target - nums[i]] = i
}
return []int{0, 1}
}
JS
// 1. Two Sum (3/14/53371)
// Runtime: 72 ms (82.97%) Memory: 39.42 MB (94.91%)
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
const twoSum = function(nums, target) {
let table = {};
for(var i = 0; i < nums.length; i++) {
if(table[nums[i]] >= 0) {
return [table[nums[i]], i];
}
table[target - nums[i]] = i;
}
};