两数之和
2015-12-11 13:02
260 查看
给一个整数数组,找到两个数使得他们的和等于一个给定的数target。
你需要实现的函数twoSum需要返回这两个数的下标, 并且第一个下标小于第二个下标。注意这里下标的范围是1到n,不是以0开头。
您在真实的面试中是否遇到过这个题?
Yes
样例
numbers=[2, 7, 11, 15], target=9
return [1, 2]
注意
你可以假设只有一组答案。
你需要实现的函数twoSum需要返回这两个数的下标, 并且第一个下标小于第二个下标。注意这里下标的范围是1到n,不是以0开头。
您在真实的面试中是否遇到过这个题?
Yes
样例
numbers=[2, 7, 11, 15], target=9
return [1, 2]
注意
你可以假设只有一组答案。
public class Solution { /* * @param numbers : An array of Integer * @param target : target = numbers[index1] + numbers[index2] * @return : [index1 + 1, index2 + 1] (index1 < index2) */ public int[] twoSum(int[] numbers, int target) { // write your code here int[] a = new int[2]; for(int i=0;i<numbers.length;i++) for(int j=i+1;j<numbers.length;j++) if(numbers[i] + numbers[j] == target) { a[0] = i+1; a[1] = j+1; } Arrays.sort(a); return a; } }
相关文章推荐
- 三数之和 II——LintCode
- Count Primes
- SPOJ COT Count on a tree
- APP原型设计工具,哪家强?转自知乎
- Cocos2d-x 脚本语言Lua基本语法
- 三数之和——LintCode
- rails 4 里面 用 link_to 来生成 delete调用,
- 十大编程算法助程序员走上高手之路
- Centos查看端口占用情况和开启端口命令
- Hadoop教程(四):理解MapReduce、MapReduce计数器和连接、MapReduce Hadoop程序连接数据
- MyEclipse提示注册码MyEclipse Trial Expired解决方案
- 派生类到基类的转换 和基类到派生类的转换
- linux硬链接与软链接
- Gson解析内存溢出
- 凸包 Codeforces605C Freelancer's Dreams
- Android学习笔记(15):网格布局GridLayout
- json_encode 数值类型转换
- Hadoop教程(三):HDFS、MapReduce、程序入门实践
- StoryBoard页面跳转方式 Show,Show Detail,Present Modally,Present as Popover
- 一起读 Gevent 源码