1. 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:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解析1:
1 | class Solution { |
十分暴力的写法,时间复杂度为O(n^2),直接遍历容器,寻找到下标不同,并且相加等于target的下标,然后返回
解析2:
1 | class Solution { |
解析2的算法时间复杂度为O(n)理解解析2需要理解 map容器map
容器是一个存放关键字和值对的容器,关键字可以是任意类型,直接访问关键字下标可以得到对应的值,用到了C++STL
里面的unordered_map
首先定义一个std::unordered_map<int, int> hash
和 std::vector<int> result
还有我们需要的数wanted_num
进入循环,
1 | for (int i = 0; i < nums.size(); i++) { |
访问nums
的每一个元素,进入判定
- 如果
wanted_num
在hash
里的话,就把wanted_num
的索引和当前的i
放入result中,作为最后结果 - 如果没有在
hash
表里面,当前的元素放入hash表里,并设置下标为i
最后一定会把wanted_num
放进hash表中,即解
时间复杂度O(n)