博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Two Sum--两数之和
阅读量:4107 次
发布时间:2019-05-25

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

问题:

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

解答:

哈希的思想,将每个数存为数对pair(num, index), 遍历数组的时候 查找target-num是否存在,如果存在取出index.

class Solution {public:	vector
twoSum(vector
&numbers, int target) { map
my_map; vector
m_result; for(int i= 0; i<=numbers.size();i++) { if(my_map.count((target-numbers[i])) == 1) { m_result.push_back(my_map[target-numbers[i]]+1); m_result.push_back(i+1); break; } else { my_map[numbers[i]] = i; } } return m_result; }};

转载地址:http://rztsi.baihongyu.com/

你可能感兴趣的文章
CString 成员函数用法大全
查看>>
如何让静态局部和全局变量或数组存在指定地址的Flash
查看>>
网络分析仪基础(续)
查看>>
_cdecl与_stdcall调用约定
查看>>
比较IC卡、ID卡、M1卡、CPU卡它们之间有什么区别?
查看>>
轻松掌握ISO8583报文协议
查看>>
8583协议深入理解 2
查看>>
STM32之中断与事件---中断与事件的区别
查看>>
STM32之CAN ---CAN ID过滤器分析
查看>>
PBOC/EMV之静态数据认证(SDA)与动态数据认证(DDA)
查看>>
BCD码
查看>>
Hash
查看>>
对称加密 和 非对称加密
查看>>
如何在 Notepad++ 開啟「分割視窗」同時檢視、比對兩份文件?
查看>>
Notepad++ 分割視窗的兩邊同時展示兩個不同文件的內容
查看>>
delphi Random()函数
查看>>
delphi 中 delete的用法
查看>>
MFC中char*,string和CString之间的转换
查看>>
COMMTIMEOUTS详解
查看>>
网络通信时字节序转换原理与网络字节序、大端和小端模式
查看>>