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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
tag:
方法一:暴力破解
时间复杂度O(N2)
竟然Accepted :)
方法二:哈希表
时间复杂度O(N), 空间复杂度O(N);
java
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0; i< nums.length; i++) {
if(map.containsKey(target-nums[i])) {
return new int[]{map.get(target-nums[i]), i};
} else {
map.put(nums[i], i);
}
}
return null;
}
go
func twoSum(nums []int, target int) (int, int) {
sort.Ints(nums)
for i, j := 0, len(nums)-1; i < j; {
if nums[i]+nums[j] == target {
return i, j
} else if nums[i]+nums[j] < target {
i++
} else {
j--
}
}
return 0, len(nums) - 1
}
方法三:排序,逼近
时间复杂度O(NLogN)