本文共 1522 字,大约阅读时间需要 5 分钟。
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].
class Solution { public int[] twoSum(int[] nums, int target) { int[] res = new int[2]; if(nums == null || nums.length <= 1) return res; HashMapmap = new HashMap (); for(int i = 0; i < nums.length; i++){ int val = target - nums[i]; if(map.containsKey(val) && map.get(val) != i){ res[0] = i; res[1] = map.get(val); return res; }else map.put(nums[i], i); } return res; }}
2019.12.17 update:
因为结果与index无关,可以对原数组先排序,再用双指针。 空间复杂度为O(1),时间复杂度为O(nlogn)。不过这个方法为何时间复杂度是nlogn我还是没有太想清楚public class Solution { public int[] twoSum(int[] numbers, int target) { Arrays.sort(numbers); int L = 0, R = numbers.length - 1; while (L < R) { if (numbers[L] + numbers[R] == target) { int[] pair = new int[2]; pair[0] = numbers[L]; pair[1] = numbers[R]; return pair; } if (numbers[L] + numbers[R] < target) { L++; } else { R--; } } return null; }}
转载地址:http://qyqvb.baihongyu.com/