Leetcode 刷题指北 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].

解题思路

时间复杂度:O(n)
1、用一个map保存已遍历的value到index的映射。
2、遍历数组,用target与当前value的差值查找map,如果存在则可以直接返回结果。
3、不存在,则将当前value到index的映射存储到map中供后续遍历使用。
4、利用map就不必对于每个value都重新遍历一次数组查找对应的差值。map的访问时间是O(1)的。

解题源码

#include<vector>
#include<iostream>
#include<map>
using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int, int> value_index_map;
        vector<int> res;
        int len = nums.size();

        for (int i = 0; i < len; ++i) {
            int d = target - nums[i];

            if (value_index_map.find(d) != value_index_map.end()) {
                res.push_back(value_index_map[d]);
                res.push_back(i);
                return res;
            }
            else
            {
                value_index_map[nums[i]] = i;
            }
        }

        return res;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容