博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Two Sum
阅读量:4359 次
发布时间:2019-06-07

本文共 848 字,大约阅读时间需要 2 分钟。

 

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].

寻找两数之和,利用map存储数组的值与索引,然后遍历数组找出map中的元素,返回元素的索引。需要注意的是返回的结果索引不能相等。

class Solution {public:    vector
twoSum(vector
& nums, int target) { unordered_map
m; for (int i = 0; i != nums.size(); i++) m[nums[i]] = i; for (int i = 0; i != nums.size(); i++) { int diff = target - nums[i]; if (m.count(diff) && m[diff] != i) return {i, m[diff]}; } }};// 6 ms

 

转载于:https://www.cnblogs.com/immjc/p/7510780.html

你可能感兴趣的文章
Android 彩色Toast实现
查看>>
设计模式六大原则(2):里氏替换原则
查看>>
curl应用总结 转载
查看>>
C++ 类的对象管理模型初讲
查看>>
企业应用架构读书笔记与总结
查看>>
查看系统信息命令大全
查看>>
awk,rsync,重启,maxdepth一层目录,登录,开机自启动
查看>>
代码回顾
查看>>
对一次系统上线的思考-走出“舒适区”
查看>>
【06】Cent OS 7 中部署 zabbix_server 环境
查看>>
vue 中 vue-router、transition、keep-alive 怎么结合使用?
查看>>
小常识
查看>>
TungstenSecret
查看>>
LR遇到的问题
查看>>
51nod 1010 只包含因子2 3 5的数 && poj - 1338 Ugly Numbers(打表)
查看>>
在OS X 10.11 中使用 "apue.h" (3rd Edition)
查看>>
mysql 批量插入更新
查看>>
ubuntu 实用命令收集
查看>>
[算法]分治算法(Divide and Conquer)
查看>>
mssql格式化工具——SQL PRETTY PRINTER
查看>>