1. Two Sum[Easy]

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].
#include <map>
#include <iterator>

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int, int> m;
        vector<int> v(2);
        map<int, int>::iterator iter;
        for(int i = 0; i < nums.size(); ++i){
            iter = m.find(target - nums[i]);
            if(iter != m.end()){
                v[0] = iter->second, v[1] = i;
                break;
            }
            m[nums[i]] = i;
        }
        return v;
    }
};
Runtime: 12 ms, faster than 93.28% of C++ online submissions for Two Sum.
Memory Usage: 10.1 MB, less than 54.10% of C++ online submissions for Two Sum.
思路
  • 遍历数组,插入<value, index>之前查找是否存在key=value(避免出现重复的key)
  • 存在则return [index, i], 不存在继续遍历
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容