给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
1.第一想法
双层for循环
java:
private static int[] twoSumDoubleLoop(int[] nums, int target) {for (int i = 0; i<nums.length-1; i++){for (int j=i+1; j<nums.length; j++){if (nums[i]+nums[j] == target){return new int[]{i, j};}}}return null;
}
scala:
def twoSumDoubleLoop(nums: Array[Int], target: Int): Array[Int] = {for (i <- 0 until nums.length-1; j <- i + 1 until nums.length){if (nums(i)+nums(j) == target){return Array(i, j)}}throw new Exception("not found@!")}
2.第二想法
映射表实现
java:
private static int[] twoSumHashMap(int[] nums, int target) {int[] res = new int[2];HashMap<Integer, Integer> map = new HashMap<>();for (int i = 0; i < nums.length; i++){if (map.containsKey(nums[i])){res[0] = map.get(nums[i]);res[1] = i;}map.put(target-nums[i], i);}return res;
}
scala:
def twoSumHashMap(nums:Array[Int], target:Int): Array[Int] = {val map = new mutable.HashMap[Int, Int]()for (i <- nums.indices){if (map.contains(nums(i))){return Array(map(nums(i)), i)}
// map(target-nums(i)) = imap.+=((target-nums(i),i))}throw new Exception("not found@!")}