# Two Sum: find two number from array of integers and thats sum equal to target integer

258 views

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 + nums == 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]```

Farjanul Changed status to publish July 27, 2022
0

O(n2) runtime, O(1) space – Brute force:

The brute force approach is simple. Loop through each element x and find if there is another value that equals to target – x. As finding another value requires looping through the rest of array, its runtime complexity is O(n2).

O(n) runtime, O(n) space – Hash table:
We could reduce the runtime complexity of looking up a value to O(1) using a hash map

that maps a value to its index.

Solution in Java

```public class Solution {
// example in leetcode book
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int x = nums[i];
if (map.containsKey(target - x)) {
return new int[]{map.get(target - x), i};
}
map.put(x, i);
}
throw new IllegalArgumentException("No two sum solution");
}
}```

Solution in Python

```class Solution(object):
def twoSum(self, nums, target):
# two point
nums_index = [(v, index) for index, v in enumerate(nums)]
nums_index.sort()
begin, end = 0, len(nums) - 1
while begin < end:
curr = nums_index[begin] + nums_index[end]
if curr == target:
return [nums_index[begin], nums_index[end]]
elif curr < target:
begin += 1
else:
end -= 1
if __name__ == '__main__':
# begin
s = Solution()
print s.twoSum([3, 2, 4], 6)```

Farjanul Changed status to publish July 27, 2022
0
You are viewing 1 out of 1 answers, click here to view all answers.