description
Given an integer array nums and a target value target, and ask you to identify the target value of the two integers in the array, and return to their array subscript
Examples
given nums = [2, 7, 11 , 15], target = 9
because nums [0] + nums [1 ] = 2 + 7 = 9
is returned [0, 1]
Thinking
- Violence: two for loops
- Enhanced method (recommended, O (n) as required to return its subscript, more convenient): use the dictionary to find is O (1)
{Number needed: Who am I} through each number, if I'm not needed, I went to put my needs who wrote in the dictionary
- The third method (O (nlogn): first save the subscript of each number, the reordering O (nlogn), using two pointers (sort need to be known, and the target is greater than or less than the target to which the pointer moves)
answers - python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# {需要的差值:index}
d={}
for i in range(len(nums)):
if d.get(nums[i]) is not None: #第二个参数不写,默认返回None,注意返回0时,也会被当作false
return [d.get(nums[i]), i]#i会比较大
else:
d[target-nums[i]]=i
return []
- c++
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> m;
for (int i=0; i<nums.size(); i++)
if (m.find(nums[i])!=m.end())
return {m[nums[i]], i};
else
m[target-nums[i]]=i;
return {};
}
};