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

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

 

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.

 Notice

You may assume that each input would have exactly one solution

Example

numbers=[2, 7, 11, 15], target=9

return [1, 2]

Either of the following solutions are acceptable:

  • O(n) Space, O(nlogn) Time
  • O(n) Space, O(n) Time

 

LeetCode上的原题,请参见我之前的博客。

 

class Solution {public:    /*     * @param numbers : An array of Integer     * @param target : target = numbers[index1] + numbers[index2]     * @return : [index1+1, index2+1] (index1 < index2)     */    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 t = target - nums[i]; if (m.count(t) && m[t] != i) { return {i + 1, m[t] + 1}; } } return {}; }};

 

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

你可能感兴趣的文章
我的友情链接
查看>>
linux下查看nginx,apache,mysql,php编译命令
查看>>
JQUERY学习第三天之浮动和弹出窗口
查看>>
python中asynchat异步socket命令/响应处理
查看>>
动态编译
查看>>
linux下批量解压缩
查看>>
使用xcopy进行日增量备份
查看>>
知之者不如好之者,好之者不如乐之者
查看>>
测试Application.Idle
查看>>
sizeof与strlen的区别与联系
查看>>
Citrix发布支持Framehawk技术的HDX协议,用户体验优势进一步扩大
查看>>
Android各种访问权限Permission详解
查看>>
RHEL5.5安装中文支持
查看>>
web前端开发中浏览器兼容问题(五)
查看>>
小博老师解析Java核心技术 ——动态解析Jar的运用
查看>>
我的友情链接
查看>>
博为峰Java技术文章 ——JavaSE Swing BoxLayout布局管理器I
查看>>
PC时代的20位英雄
查看>>
经典的MySQL 数据备份daemon程序
查看>>
腾讯云TDSQL审计原理揭秘
查看>>