博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Two Sum
阅读量:4670 次
发布时间:2019-06-09

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

1. Question

给一整数数组,找两个数,使其和正好是给定值。函数 twoSum应当返回两个数的索引,且index1小于index2。索引不是从0开始的。

假设每个输入都正好有一个解。

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=9Output: index1=1, index2=2

2. Solution

最优方案时间复杂度O(n)

2.1 O(n2) solution

用两个循环遍历所有数对,找到符合要求的。

2.2 O(nlogn) solution

方案一:采用二叉搜索

  1. 数组按升序排序(采用map存储数组值和索引)
  2. 遍历数组,假设每个值是两个数的其中一个值,采用二叉搜索查找另一个值。
1 import java.util.ArrayList; 2 import java.util.Arrays; 3 import java.util.Collections; 4 import java.util.Comparator; 5 import java.util.Map.Entry; 6 import java.util.HashMap; 7  8 public class Solution { 9     public int[] twoSum( int[] numbers, int target ){10         HashMap
map = new HashMap
();11 for( int k=0; k
> num = new ArrayList
>( map.entrySet() );15 Comparator
> comp = new Comparator
>(){16 public int compare( Entry
e1, Entry
e2 ){17 return e1.getValue() - e2.getValue();18 }19 };20 Collections.sort( num, comp);21 22 //get the sorted array, n time23 int[] sorted = new int[numbers.length];24 for( int k=0; k
mid )33 i--;34 int index1;35 int index2;36 for( index1=0; index1<=i; index1++ ){37 index2 = Arrays.binarySearch( sorted, i+1, sorted.length, target - sorted[index1] );38 if( index2 >0 ){39 index1 = num.get(index1).getKey()+1;40 index2 = num.get(index2).getKey()+1;41 if( index1 < index2 )42 return new int[] { index1, index2 };43 else44 return new int[] { index2, index1 };45 }46 }47 return null;48 }49 }
binary-search

 

方案二:采用双指针

  1. 数组按升序排序(注意索引)
  2. 采用双指针,一个指针head指向数组头,一个指针tail指向数组尾。判断num[head]+num[tail]:
    1. 如果和小与给定值,head++(向和增大的方向移动指针)
    2. 如果和大于给定值,tail--(向和减小的方向移动指针)
    3. 如果和等于给定值,返回相应的索引值,按要求返回。
1 import java.util.Arrays; 2  3  4 public class Solution { 5         public int[] twoSum( int[] numbers, int target ){ 6         //if and only if there are two same numbers which sum to target, for the result, there is no duplicates in the array. 7         int[] sNum = numbers.clone(); 8         Arrays.sort(sNum); 9         10         int mid = target / 2;11         if( sNum[sNum.length-1] < mid )    return null;12         13         int index1 = 0;14         int index2 = sNum.length-1;15         while( index1 < index2 ){16             int sum = sNum[index1] + sNum[index2];17             if( sum==target ){18                 for( int k=0; k
=0; k-- ){25 if( sNum[index2] == numbers[k] ){26 index2 = k;27 break;28 }29 }30 if( index1 > index2 ){31 int temp = index1;32 index1 = index2;33 index2 = temp;34 }35 return new int[] { index1+1, index2+1 };36 }37 if( sum < target )38 index1++;39 else40 index2--;41 }42 43 return null;44 }45 }
two-pointers

 

2.3 O(n) solution

采用map保存数组,数值为键,索引为值。遍历数组,如果不在map中,加入map。考察map中是否存在满足num[i]要求的数。

该方法对数组中的每个数都找是否有符合要求的另一个数,因此不会有遗漏(这是最符合人的思路的方法)。且由于采用map,找的时间为常数时间,从而算法时间复杂度O(n).

1 import java.util.Hashtable; 2  3  4 public class Solution { 5     //when using map structure, we don't need to sort the array 6     public int[] twoSum( int[] numbers, int target ){ 7         Hashtable< Integer, Integer > num = new Hashtable< Integer, Integer >(); 8         for( int i=0; i< numbers.length; i++ ){ 9             if( num.get( numbers[i]) == null )10                 num.put(numbers[i], i);11             Integer j = num.get( target - numbers[i]);12             if( j!=null && j < i )13                 return new int[] { j.intValue()+1, i+1 };14         }15         return null;16     }17 }
map

 

posted on
2015-06-10 20:56 阅读(
...) 评论(
...)

转载于:https://www.cnblogs.com/hf-cherish/p/4567252.html

你可能感兴趣的文章
一些新了解到技术
查看>>
vue.js click点击事件获取当前元素对象
查看>>
【单调栈,单调队列】总结
查看>>
LeetCode:Gas Station
查看>>
MyBatis初识(通过小实例清晰认识MyBatis)
查看>>
面对最菜TI战队,OpenAI在Dota2上输的毫无还手之力
查看>>
XCODE快捷键和功能汇总篇(不断更新)
查看>>
Servlet开发(一)
查看>>
linux下如何查看某个容器的详细信息?
查看>>
bzoj 2843: 极地旅行社
查看>>
车林通购车之家--购车计算器模块--算法js
查看>>
webpack使用教程
查看>>
MySQL学习8 - 数据的增删改
查看>>
Linux笔记(开机自动将kerne log保存到SD卡中)
查看>>
Ajax提交数据判断员工编号是否存在,及自动填充与员工编号所对应的员工姓名。...
查看>>
CodeForces 689E (离散化+逆元+组合)
查看>>
pycharm 右键无法显示unittest框架&&解决右键只有unittest 运行如何取消右键显示进行普通run...
查看>>
jQuery的选择器
查看>>
Shell 概述、截取字符操作等
查看>>
CTF/web
查看>>