Question:

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

Question Tags:

Array , Hash Table

New Words:

add up to:总计达

indices:index的复数

zero-based:从零开始的

Solution Ideas:

思路一:

两层遍历法:对于数组中的某一个数,对它及他以后的某个数求和,若和与target相等,则可确定这两值为所找的。此方式时间复杂度为O(nlogn).

思路二:

HashMap--Value-key法:求a+b=target,也就是判断a和target-a是否都在这个数组中,

           遍历判断map中是否有数组中的某个值target-a,如果没有,则把a的key以value作为key存到map中,

           如果有,则所求的a,b得出来了。所求的索引值也就是a,b的索引值

           此方法时间复杂度为O(n)

两种方法都可以确保index1<index2.

只考虑时间复杂度的情况下,由O(n)<O(nlogn)知,思路二的效率更高。

Solution Java code:

  1. import java.util.Arrays;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4.  
  5. public class TwoSum {
  6.  
  7. public static void main(String[] args) {
  8. int[] numbers={2, 7, 11, 15};
  9. int target = 9;
  10. int[] twoSum = twoSum(numbers,target);
  11. System.out.println("two sum indices are " + twoSum[0] + " and " + twoSum[1]);
  12.  
  13. int[] twoSum2 = twoSum2(numbers,target);
  14. System.out.println("two sum indices are " + twoSum2[0] + " and " + twoSum2[1]);
  15. }

  16. //思路1
  17. public static int[] twoSum(int[] numbers, int target) {
  18. int i,j,sum;
  19. int[] indices = new int[2];
  20.  
  21. outfor:for (i=0;i<numbers.length;i++){
  22. for (j=i+1;j>i && j<numbers.length;j++){
  23. sum = numbers[i]+numbers[j];
  24. if (sum == target){
  25. indices[0]=i+1;
  26. indices[1]=j+1;
  27. break outfor;
  28. }
  29. }
  30. }
  31. return indices;
  32. }

  33.   //思路2
  34. public static int[] twoSum2(int[] numbers, int target) {
  35.  
  36. int[] indices = new int[2];
  37.  
  38. Map<Integer,Integer> map = new HashMap<Integer,Integer>();
  39.  
  40. for (int i=0;i<numbers.length;i++){
  41. if (map.containsKey(target-numbers[i])){
  42. indices[0]=map.get(target-numbers[i]);
  43. indices[1]=i+1;
  44. break;
  45. }
  46. map.put(numbers[i],i+1);
  47. }
  48. return indices;
  49. }
  50. }

思路2也可以使用hash table表达:

  1. public static int[] twoSum3(int[] numbers, int target) {
  2.  
  3. int[] indices = new int[2];
  4.  
  5. // Map<Integer,Integer> map = new HashMap<Integer,Integer>();
  6. Hashtable<Integer, Integer> hashtable = new Hashtable<Integer, Integer>();
  7.  
  8. for (int i=0;i<numbers.length;i++){
  9. Integer num = hashtable.get(numbers[i]);
  10. if (num == null) hashtable.put(numbers[i], i);
  11. num = hashtable.get(target-numbers[i]);
  12. if ( num != null && num < i) {
  13. indices[0] =num + 1;
  14. indices[1] = i+1;
  15. return indices;
  16. }
  17. }
  18. return indices;
  19. }

【LeetCode 1】算法修炼 --- Two Sum的更多相关文章

  1. 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)

    转自  http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...

  2. Leetcode 931. Minimum falling path sum 最小下降路径和(动态规划)

    Leetcode 931. Minimum falling path sum 最小下降路径和(动态规划) 题目描述 已知一个正方形二维数组A,我们想找到一条最小下降路径的和 所谓下降路径是指,从一行到 ...

  3. LeetCode初级算法(数组)解答

    这里记录了LeetCode初级算法中数组的一些题目: 加一 本来想先转成整数,加1后再转回去:耽美想到测试的例子考虑到了这个方法的笨重,所以int类型超了最大范围65536,导致程序出错. class ...

  4. [leetcode]364. Nested List Weight Sum II嵌套列表加权和II

    Given a nested list of integers, return the sum of all integers in the list weighted by their depth. ...

  5. LeetCode初级算法的Python实现--排序和搜索、设计问题、数学及其他

    LeetCode初级算法的Python实现--排序和搜索.设计问题.数学及其他 1.排序和搜索 class Solution(object): # 合并两个有序数组 def merge(self, n ...

  6. LeetCode初级算法的Python实现--链表

    LeetCode初级算法的Python实现--链表 之前没有接触过Python编写的链表,所以这里记录一下思路.这里前面的代码是和leetcode中的一样,因为做题需要调用,所以下面会给出. 首先定义 ...

  7. LeetCode初级算法的Python实现--字符串

    LeetCode初级算法的Python实现--字符串 # 反转字符串 def reverseString(s): return s[::-1] # 颠倒数字 def reverse(x): if x ...

  8. LeetCode初级算法的Python实现--数组

    LeetCode初级算法的Python实现--数组 # -*- coding: utf-8 -*- """ @Created on 2018/6/3 17:06 @aut ...

  9. LeetCode:算法特辑——二分搜索

    LeetCode:算法特辑——二分搜索 算法模板——基础 int L =0; int R =arr.length; while(L<R) { int M = (R-L)/2+L; if(arr[ ...

随机推荐

  1. Win7系统下利用U盘安装Ubuntu14.04麒麟版

    转自http://www.360doc.cn/article/14743053_335473181.html 重要提示:在采用u盘安装ubuntu分区时,所有磁盘一定要全部设置成逻辑分区,包括根目录/ ...

  2. Android - 应用名称设置的问题

    今天我想修改我的android应用名称,就是手机桌面上图标下面的名称,根据我的理解我修改AndroidManifest.xml文件中application标签中的android:label=" ...

  3. 在WindowsServer2008服务器上安装SQLServer2008R2

    登录服务器 使用远程桌面登录Windows Server 2008   安装前的准备工作 下载SQL Server安装程序 下载Microsoft SQL Server2008 R2 RTM - Ex ...

  4. [置顶] Linux信号相关笔记

    最近又温习了一遍Linux中的信号知识,发现有很多东西以前没有注意到,就通过这篇博客记录一下,巩固一下知识点. 一,信号基础: 信号是什么?为了回答这个问题,首先要从异常说起,这里的异常不是指c++/ ...

  5. IoC框架---通俗概述

    1 IoC理论的背景    我们都知道,在采用面向对象方法设计的软件系统中,它的底层实现都是由N个对象组成的,所有的对象通过彼此的合作,最终实现系统的业务逻辑.  图1:软件系统中耦合的对象 如果我们 ...

  6. sql reiserror 输出错误

    其语法如下: RAISERROR ( { msg_id | msg_str | @local_variable }                    { ,severity ,state }    ...

  7. android 解释dp,px,pt,sp单位

    1.dp(dip):不同设备有不同的显示效果,这个和设备硬件有关系,一般我们为了支持WVGA,HVGA和QVGA对剑使用这个,它是不依赖像素的 2.px:pixels(像素),不同设备显示效果相同,一 ...

  8. wikioi 1098 均分纸牌

    题目描述 Description 有 N 堆纸牌,编号分别为 1,2,-, N.每堆上有若干张,但纸牌总数必为 N 的倍数.可以在任一堆上取若于张纸牌,然后移动. 移牌规则为:在编号为 1 堆上取的纸 ...

  9. js 判断pc与手机

    var u = navigator.userAgent; if ((u.indexOf('Mac') > -1 || u.indexOf('Windows') > -1) &&am ...

  10. java中Arrays类中,binarySearch()方法的返回值问题

    最近在复习Java知识,发现果然不经常使用忘得非常快... 看到binarySearch()方法的使用时,发现书上有点错误,于是就自己上机实验了一下,最后总结一下该方法的返回值. 总结:binaryS ...