给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
复制 输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。 示例 2:
复制 输入:nums = [3,2,4], target = 6
输出:[1,2] 示例 3:
复制 输入:nums = [3,3], target = 6
输出:[0,1] 提示:
进阶: 你可以想出一个时间复杂度小于 O(n2) 的算法吗?
英文题目: 2 sum (Two sum)
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target . You may assume that each input would have **_exactly one solution**, and you may not use the same element twice. You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9 Output: [0,1]
Explaination: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2]
Example 3: Input: nums = [3,3], target = 6 Output: [0,1]
Constraints:
Only one valid answer exists.
方法1 : 暴力法,复杂度O(n^2),会TLE(超时).
方法2 : 双指针法, 固定一个, 找另一个. 发现第一次出现nums[i] + nums[j] == target就返回结果.
方法3 : hashmap查表,在表中找 target - 当前循环变量i对应的那个数。用一个哈希表(C++中用unordered_map, C#中用dictionary, Python中用dict,Java中可以直接用HashMap),存储每个数对应的下标,复杂度O(n);
方法4 : 快排 + 双指针
定义一个struct, 存储 index 和 value
left自增, right 自减
注意 : 如果要在一个struct上调用STL中的sort方法,需要先为其定义好 compare 函数。
具体代码如下: