Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

直接暴力法O(n*n)超时,因此需采用hashmap,这里采用map来存储数据并进行搜索,其实现为

复制代码
 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4        vector<int> res;
 5        map<int,int> tmp;
 6        for(int i=0;i<nums.size();i++)
 7        {
 8            if(!tmp.count(nums[i]))
 9                tmp.insert(pair<int,int>(nums[i],i+1));
10            if(tmp.count(target-nums[i]))
11            {
12                int n=tmp[target-nums[i]];
13                if(n<i+1)
14                {
15                    res.push_back(n);
16                    res.push_back(i+1);
17                    return res;
18                }
19            }
20        }
21        return res;
22     }
23 };
复制代码

 

红黑树。

posted @   鸭子船长  阅读(169)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示