面试题: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:
iven nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
我的解法:最简单的大圈套小圈。
1 public int[] twoSum(int[] nums, int target) { 2 for (int i = 0; i < nums.length; i++) { 3 for (int j = i + 1; j < nums.length; j++) { 4 if (nums[j] == target - nums[i]) { 5 return new int[] { i, j }; 6 } 7 } 8 } 9 throw new IllegalArgumentException("No two sum solution"); 10 }
快速解法:通过HashMap将数组中元素的值和索引对应起来。 涉及到值-索引这种对应关系的,第一时间想到HashMap。
1 public int[] twoSum(int[] nums, int target) { 2 Map<Integer, Integer> map = new HashMap<>(); 3 for (int i = 0; i < nums.length; i++) { //第一个循环讲元素值和索引放入HashMap中 4 map.put(nums[i], i); 5 } 6 for (int i = 0; i < nums.length; i++) { 7 int complement = target - nums[i]; 8 if (map.containsKey(complement) && map.get(complement) != i) { //不能重复使用,所以!=i 9 return new int[] { i, map.get(complement) }; 10 } 11 } 12 throw new IllegalArgumentException("No two sum solution"); 13 }
更优解法:在放入HashMap的同时检查是否有满足条件的key。
1 public int[] twoSum(int[] nums, int target) { 2 Map<Integer, Integer> map = new HashMap<>(); 3 for (int i = 0; i < nums.length; i++) { 4 int complement = target - nums[i]; 5 if (map.containsKey(complement)) { 6 return new int[] { map.get(complement), i }; 7 } 8 map.put(nums[i], i); 9 } 10 throw new IllegalArgumentException("No two sum solution"); 11 }