1. 题目

1.1 英文题目

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

1.2 中文题目

给定一个整数数组nums,返回数组中“和是某个给定值target”的两个数的下标。假设对于每次输入有且只有一个解。

1.3输入输出

输入 输出
nums = [2,7,11,15], target = 9 [0,1]
nums = [3,2,4], target = 6 [1,2]
nums = [3,3], target = 6 [0,1]

2. 实验平台

IDE:VS2019

IDE版本:16.10.1

语言:c++

3. 代码

3.1 功能程序

#pragma once
#include<vector>
#include<map>
using namespace std; //主功能
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
map<int, int> hashMap; // 声明哈希表,存储已经遍历过的nums,其中nums的元素为key,元素的索引为value
vector<int> ans; // 存储结果
for (int i = 0; i < nums.size(); i++) // 遍历nums
{
int temp = target - nums[i]; // 定义target与nums[i]的差值
if (hashMap.count(temp)) // 向前搜索是否有与差值相同的元素,若有
{
ans = { hashMap[temp], i }; // 给出结果
}
hashMap[nums[i]] = i; // 将遍历过的nums[i]加入到哈希表hashMap中
}
return ans; // 返回结果
}
};

3.2 测试程序

#include "Solution.h"
#include <vector>
#include<iostream>
using namespace std; // 主程序
void main()
{
vector<int> nums = { 1,1,2,7,4,2,5 };
int target = 4; // 定义输入
Solution solution; // 实例化Solution
vector<int> result = solution.twoSum(nums, target); // 主算法
cout << "[" << result[0] << "," << result[1] << "]" << endl; // 输出结果
}

4. 代码思路

构建哈希表,每次循环搜索时,都从搜索当前位置到前面几个元素进行查找

5. 注意事项

哈希表会对相同的key值的value进行覆盖处理,这一点需要加以注意。

最新文章

  1. 如何写出安全的API接口(参数加密+超时处理+私钥验证+Https)- 续(附demo)
  2. Js解析浏览器路径的方法
  3. InnoDB锁机制分析
  4. 【PHP绘图技术&amp;&amp;验证码绘制】
  5. HTML 事件属性(下)
  6. Linux新手学堂 Crontab命令的语法
  7. Construct a basic automation test framework
  8. 【ASP.Net MVC】在AspNet Mvc使用JQuery AutoComplete组件
  9. HDU5804 Price List (BestCoder Round #86 A)水题
  10. WP8异常错误:Error HRESULT E_FAIL has been returned from a call to a COM component.
  11. struct2访问或添加request/session/application
  12. Java的序列化与反序列化(一):初识
  13. Android 基本控件
  14. android入门——UI(6)——ViewPager+Menu+PopupWindow
  15. Spring面试问答Top 25
  16. tp框架链接数据库的基本操作
  17. vue项目构建与实战
  18. Hibernte
  19. Angular cli 发布自定义组件
  20. HDU 4764 Stone(巴什博奕)

热门文章

  1. redux 源码浅析
  2. 痞子衡嵌入式:关于i.MXRT中FlexSPI外设lookupTable里配置Normal read的一个小误区
  3. ICCV2019论文点评:3D Object Detect疏密度点云三维目标检测
  4. 2.5D Visual Sound:CVPR2019论文解析
  5. SpringBoot原理深入及源码剖析(一) 依赖管理及自动配置
  6. HashMap底层实现原理及面试常见问题
  7. CentOS 7服务管理
  8. 回顾Games101图形学(一)几何变换中一些公式的推导
  9. 可扩展的 Web 架构与分布式系统
  10. 百炼 POJ2393:Yogurt factory【把存储费用用递推的方式表达】