题解 | #两数之和#

两数之和

https://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f

class Solution {
public:
    /**
     * 
     * @param numbers int整型vector 
     * @param target int整型 
     * @return int整型vector
     */
    vector<int> twoSum(vector<int>& numbers, int target) {
	  // 定义一个哈希表,unordered_map和map数据结构都可以;unordered_map底层实现是哈希表,复杂度是O(1);map底层实现是红黑树
	  // 键:元素	值:元素在数组中的位置(从1开始算)
        unordered_map<int, int> hashmap;
	  // 遍历数组
        for(int i = 0; i < numbers.size(); ++i){
		  // 哈希表为空的时候,把第一个元素加入到哈希表里
            if(hashmap.empty()){
                hashmap.insert(make_pair(numbers[i], i + 1));	// 值是位置,所以要在索引i的基础上+1
                continue;
            }
		  // 如果哈希表里能找到 target - 当前索引元素 的键,说明找到满足题意的两个数
            if(hashmap.find(target - numbers[i]) != hashmap.end()){
                return {hashmap.find(target - numbers[i])->second, i + 1};	// 直接返回两个数在数组中的位置
            } else {
			  // 没找到 target - 当前索引元素 的键,把当前索引i的元素加入到哈希表中
                hashmap.insert(make_pair(numbers[i], i + 1));
            }
        }
        return {};
    }
};

因为题目说明肯定能找到两数之和为target,最后返回的数组也只有两个元素,所以不需要定义结果数组:vector<int> res;

另外,哈希表里存储的元素的下标,题目要求从1开始,而遍历numbers数组时,下标是从0开始的,往哈希表里存储元素索引的时候,要+1。

其实加不加1都可以,无非就是返回结果数组的第一个元素要不要+1,如果存在哈希表里的键值对的值是索引,返回的第一个元素要+1;是位置,不需要+1~~~

全部评论

相关推荐

点赞 评论 收藏
分享
自由水:这HR已经很好了,多的是已读不回和不读了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务