Two Sum
来源:互联网 发布:js 集合:{} 编辑:程序博客网 时间:2024/04/28 13:45
Mar 14 '11
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
记录原始下标,然后排序。由于是有序的,如果当前和大于target,那么只有增大start下标才有可能得出解。同理,当和小于target时,只有减小end才有可能得到解。排序所用时间O(nlogn),之后的判断O(n)。总的时间复杂度为O(nlogn)
import java.util.Arrays;class Pair implements Comparable<Pair>{public int val;public int index;@Overridepublic int compareTo(Pair o) {return this.val-o.val;}}public class Solution {public int[] twoSum(int[] numbers, int target) {Pair pairs[] = new Pair[numbers.length]; for(int i=0;i<numbers.length;++i){ pairs[i] = new Pair();pairs[i].index = i;pairs[i].val = numbers[i];} Arrays.sort(pairs); int i=0, j=numbers.length-1; while(i < j){ int sum = pairs[i].val + pairs[j].val; if( sum == target){ int[] res = new int[2]; res[0] = Math.min(pairs[i].index, pairs[j].index) + 1; res[1] = Math.max(pairs[i].index, pairs[j].index) + 1; return res; }else if(sum > target) j--; else i++; } return null;}/*public static void main(String[] args) {//[5,75,25], 100int[] array = {2, 7, 11, 15};Solution solution = new Solution();System.out.println(Arrays.toString(solution.twoSum(array, 9)));}*/}
- Two Sum
- Two Sum
- Two Sum
- two sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- 连接字符串
- C#中的快捷键,可以更方便的编写代码
- 一步步构建大型网站架构
- 用 ElementTree 在 Python 中解析 XML
- Axis 调用Soap代理模式设计
- Two Sum
- git 添加忽略列表
- 探秘SensorHAL
- repeater 分页后取不到下一页的数据
- 1、GZIP压缩格式简介
- 出现未声明的标识符问题
- 用distcc和dmucs在ubuntu 10.04上搭建分布式编译环境
- 程序员面试 挺好的…………有感触!
- 第一次写Windows服务的几点心得(C#/VS2003)