[leetcode 1] Two Sum

来源:互联网 发布:数据库的主要功能 编辑:程序博客网 时间:2024/04/20 06:25

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

思路1:排序,在夹逼。时间复杂度高一些

思路2:用哈希表储存变量,健为number的值,值为其index。下面的代码实现是思路2

class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        unordered_map<int, int> map;        vector<int> res;        for (auto i = 0; i < numbers.size(); i++) {            map[numbers[i]] = i;        }        for (auto i = 0; i < numbers.size(); i++) {            int gap = target - numbers[i];            if (map.find(gap) != map.end() && map[gap] > i) {                res.push_back(i+1);                res.push_back(map[gap] + 1);                break;            }        }        return res;    }};


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 棉麻裙子掉毛怎么办 10个月宝宝吃手怎么办 婴儿连体衣长了怎么办 冰丝面料变长了怎么办 t恤袖口大了怎么办 长袖t恤袖子长了怎么办 机打的扣子掉了怎么办 四个月宝宝头扁怎么办 鞋子前面穿翘了怎么办 休完产假没人带怎么办 休完产假孩子吃奶怎么办 巴布豆童鞋里面臭了到底怎么办 连体裤有点卡档怎么办 宝宝连体衣扣子掉了怎么办 买衣服被骂了怎么办? 把人车刮了跑了怎么办 打工打不下去了怎么办 白色衣服变粉了怎么办 一量血压就紧张怎么办 一紧张就血压高怎么办 不在上班时间在单位受伤怎么办 生活过得太压抑怎么办 高低床踏板断了怎么办 高低床 孩子摔下来怎么办 小孩子太小高低床爬梯怎么办 辞职后单位不发工资怎么办 买了个上下床搬家怎么办 爸妈不让学日语怎么办 把共享单车弄坏了怎么办 裙子沾到单车油怎么办? 外穿的短裤卷边怎么办 蹬完单车膝盖疼怎么办 夏天骑摩托太热怎么办 半框眼镜线断了怎么办 镜片从镜框脱了怎么办 干活累的肩膀痛怎么办 干活累的肩膀疼怎么办 骑山地车手腕和脖子疼怎么办? 布艺沙发坐软了怎么办 篮球护臂太大了怎么办 豪爵摩托车没电怎么办