Chinaunix首页 | 论坛 | 博客
  • 博客访问: 80435
  • 博文数量: 29
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 225
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-06 15:31
文章分类

全部博文(29)

文章存档

2015年(18)

2014年(11)

我的朋友

分类: Java

2015-01-14 16:44:47

题目:

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

看到题目,很容易就想出来的一种解法:

点击(此处)折叠或打开

  1. public class Solution {
  2.     public int[] twoSum(int[] numbers, int target) {
  3.         int[] result = new int[2];
  4.         int len = numbers.length;
  5.         for(int i = 0; i < len; i++){
  6.             for(int j = i+1; j < len; j++){
  7.                 if(numbers[i]+numbers[j] == target){
  8.                     result[0] = i+1;
  9.                     result[1] = j+1;
  10.             }
  11.         }
  12.         return result;
  13.     }
  14. }
但是将这种解法提交到OJ的话是不会通过的,原因在于算法的复杂度过高。而采用hashset的话可以将算法的复杂度大大降低,程序如下:

点击(此处)折叠或打开

  1. public class Solution {
  2.     public int[] twoSum(int[] numbers, int target) {
  3.         int[] result = new int[2];
  4.         int len = numbers.length;
  5.         HashMap<Integer,Integer> myhashmap = new HashMap<Integer,Integer>();
  6.         for(int i = 0; i < len; i++){
  7.             Integer diff = Integer.valueOf(target - numbers[i]);
  8.             if(myhashmap.containsKey(diff)){
  9.                 result[0] = myhashmap.get(diff);
  10.                 result[1] = i+1;
  11.             }
  12.             myhashmap.put(Integer.valueOf(numbers[i]), Integer.valueOf(i+1));
  13.         }
  14.         return result;
  15.     }
  16. }

                                                                                                                                                
                                                         

阅读(600) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~