CODE 129: Two Sum
来源:互联网 发布:毕业生就业数据 编辑:程序博客网 时间:2024/05/16 18:24
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
public int[] twoSum(int[] numbers, int target) {// IMPORTANT: Please reset any member data you declared, as// the same Solution instance will be reused for each test case.if (null == numbers || numbers.length <= 1) {return new int[] {};}int[] tmp = new int[numbers.length];int[] results = new int[2];for (int i = 0; i < numbers.length; i++) {tmp[i] = numbers[i];}Arrays.sort(tmp);int start = 0;int end = tmp.length - 1;while (start < end) {if (tmp[start] + tmp[end] < target) {start++;} else if (tmp[start] + tmp[end] > target) {end--;} else {break;}}for (int i = 0; i < numbers.length; i++) {if (numbers[i] == tmp[start] || numbers[i] == tmp[end]) {results[0] = i + 1;break;}}for (int i = numbers.length - 1; i >= results[0] - 1; i--) {if (numbers[i] == tmp[start] || numbers[i] == tmp[end]) {results[1] = i + 1;break;}}return results;}
- CODE 129: Two Sum
- Lette Code Two Sum
- leetcode 日经贴,Cpp code -Two Sum
- Leet Code Medium 1 two sum
- 【Leet Code- Algorithm】【1-Two Sum】【Python】
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Two Sum
- Two Sum
- Two Sum
- two sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- effective C++笔记(二)
- hdu4508 完全背包
- CMD命令-adb相关
- Time
- zigbee提取RSSI值
- CODE 129: Two Sum
- MyEclipse 2013(professional) 破解方法
- 测试印象笔记公开链接,看搜索引擎能否搜索到
- poj 2299 Ultra-QuickSort
- 机房收费系统之上机过程
- 八连块(类似水池数目(nyoj27),水池问题只有四个方向, 八连快有八个方向)
- 开始用cocos2d 写个简单魔塔
- VIM 多窗口操作
- Review some key points of Git