码迷,mamicode.com
首页 > 其他好文 > 详细

twoSum

时间:2015-04-10 23:44:22      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

 1 package code;
 2 
 3 /* Given an array of integers, find two numbers such that they add up to a specific target number.
 4 
 5 The function twoSum should return indices of the two numbers such that they add up to the target, 
 6 where index1 must be less than index2. Please note that your returned answers (both index1 and index2) 
 7 are not zero-based.
 8 
 9 You may assume that each input would have exactly one solution.
10 Input: numbers={2, 7, 11, 15}, target=9
11 Output: index1=1, index2=2

  给定一个数组,寻找在这个数组中是否存在两个数之和为某个定值。


  要点:


  1、一个数就是一个数,比如[2, 1],寻找和为4时,不能使用2+2。


  2、需要输出位置。

  3、要考虑时间复杂度,两个for循环的时间复杂度是O(N^2),为了降低时间复杂度,可以利用HashMap。

   思路是循环一次,每次都判断当前数组索引位置的值在不在hashtable里,不在的话,加入进去,key为数值,value为它的索引值;在的话,取得他的key,记为n(此时n一定小于循环变量i),接下来再在h    ashtable中查找(target-当前数值)这个数,利用了hashtable中查找元素时间为常数的优势,如果找到了就结束,此处需要注意的是,如果数组中有重复的值出现,那么第二次出现时就不会加入到hasht    able里了,比如3,4,3,6;target=6时,当循环到第二个3时,也可以得到正确结果。

 

12 */
13 
14 import java.util.HashMap;
15 
16 
17 public class TwoSum {
18 
19     //遍历两次数组,时间复杂度为O(N^2) ,不符合要求
20     public int[] twoSum(int[] array,int target){
21         int[] result = new int[2];
22         int length = array.length;
23         out:for(int i = 0;i<length-1;i++){
24             for(int j = i+1;j<length;j++){
25                 if(array[i] + array[j] == target){
26                     result[0] = i;
27                     result[1] = j;
28                     break out;
29                 }
30                 
31             }
32             
33             if((i == length-2) && (array[i] + array[i+1]) != target){
34                 result[0] = -1;
35                 result[1] = -1;
36             }
37         }
38         return result; 
39     }
40     
41     //1.时间复杂度降为O(n)
42     //2.考虑出现同样数字的情况,如果map中已经有该数字,则不add进map中。第一个相同数字的下标根据map的get函数获取,
43     //第二个相同数字的下标由i记录
44     public int[] twoSum2(int[] array,int target){
45         int[] a = new int[2];
46         HashMap<Integer,Integer> nums = new HashMap<Integer,Integer>();
47         for(int i = 0;i<array.length;i++){
48             Integer n = nums.get(array[i]);
49             if(n == null)
50                 nums.put(array[i],i);
51             n = nums.get(target-array[i]);
52             if(n!=null && n<i){
53                 a[0] = n+1;
54                 a[1] = i+1;
55                 return a;
56                 }
57         }
58         return a;
59         
60     }
61 }


 

twoSum

标签:

原文地址:http://www.cnblogs.com/myclover/p/4415898.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!