1. Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Solution
(1) Java
class Solution {
public int[] twoSum(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return new int[]{-1,-1};
}
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target-nums[i])) {
return new int[]{map.get(target-nums[i]), i};
}
map.put(nums[i], i);
}
return new int[]{-1,-1};
}
}
(2) Python
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if not nums:
return []
cache = {}
for i, num in enumerate(nums):
if target-num in cache:
return [cache[target-num], i]
cache[num] = i
return []
(3) Scala
object Solution {
def twoSum(nums: Array[Int], target: Int): Array[Int] = {
nums.zipWithIndex.filter(x =>
(nums.take(nums.indexOf(x._1)) ++ nums.drop(nums.indexOf(x._1)+1))
.contains(target - x._1)).map(_._2)
}
}