题目: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

 class Solution
{
public:
vector<int> twoSum(vector<int> &numbers, int target)
{
vector<int> ret(, -);
map<int, int> m;
for (int i = ; i < numbers.size(); i++)
{
if (m.find(target - numbers[i]) == m.end())
m[numbers[i]] = i;
else
{
ret[] = m[target - numbers[i]] + ;
ret[] = i + ;
return ret;
} }
}
};

  Java版本:

public class Solution
{
public int[] twoSum(int[] nums, int target)
{
int reslut[]=new int[2];
boolean tag=false;
for(int i=0;i<nums.length-1;i++)
{
int j=i+1;
while(j<nums.length)
{
if(nums[i]+nums[j]==target)
{
reslut[0]=i+1;
reslut[1]=j+1;
tag=true;
break;
}
else
{
j++;
}
}
if(tag)
break;
}
return reslut;
}
}

最新文章

  1. Ant_build.xml的最完整解释
  2. 一次诡异的TOMCAT启动故障的解决
  3. SecureCRT清屏
  4. IT公司100题-6-根据上排给出十个数,在其下排填出对应的十个数
  5. Animations--动画基础
  6. JTA事务管理--配置剖析
  7. spring heibernate 调用存储过程
  8. POJ 3177 Redundant Paths 边双(重边)缩点
  9. Hibernate+jxl+excel导入数据库
  10. 数据库,inner join,left join right join 的区别
  11. java listener实现定时任务
  12. UVA11983 - Weird Advertisement(扫描线)
  13. 关于freemarker 空变量的接收以及类型转换 笔记
  14. Confluence 6 管理员联系表单的后台配置界面
  15. C++基类的析构函数定义为虚函数的原因
  16. 如何去掉文件里的^M
  17. 不要问我有多懒,写个脚本跑django
  18. 2018.10.04 NOIP模拟 航班(tarjan+树形dp)
  19. COGS2294 释迦
  20. phpmyadmin打开空白

热门文章

  1. Java如何获得运行线程的优先级?
  2. JDBC创建表实例
  3. Spring JDBC调用存储函数
  4. 浅谈android中只使用一个TextView实现高仿京东,淘宝各种倒计时
  5. poj1276
  6. Ubuntu 安装IntelliJ IDEA
  7. Linux系统设置及基本操作
  8. zip压缩工具 tar打包 打包并压缩
  9. spark 修改分区(存储结果需要)
  10. jquery animate动画持续运动