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:

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

//思路1
public static int[] twoSum(int[] numbers, int target) {
int i,j,sum;
int[] indices = new int[2]; outfor:for (i=0;i<numbers.length;i++){
for (j=i+1;j>i && j<numbers.length;j++){
sum = numbers[i]+numbers[j];
if (sum == target){
indices[0]=i+1;
indices[1]=j+1;
break outfor;
}
}
}
return indices;
}

  //思路2
public static int[] twoSum2(int[] numbers, int target) { int[] indices = new int[2]; Map<Integer,Integer> map = new HashMap<Integer,Integer>(); for (int i=0;i<numbers.length;i++){
if (map.containsKey(target-numbers[i])){
indices[0]=map.get(target-numbers[i]);
indices[1]=i+1;
break;
}
map.put(numbers[i],i+1);
}
return indices;
}
}

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

public static int[] twoSum3(int[] numbers, int target) {

        int[] indices = new int[2];

//        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
Hashtable<Integer, Integer> hashtable = new Hashtable<Integer, Integer>(); for (int i=0;i<numbers.length;i++){
Integer num = hashtable.get(numbers[i]);
if (num == null) hashtable.put(numbers[i], i);
num = hashtable.get(target-numbers[i]);
if ( num != null && num < i) {
indices[0] =num + 1;
indices[1] = i+1;
return indices;
}
}
return indices;
}

【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. 使用python获得git中分支存成list

    通过这个搜集git工程下的branch信息例子,来说明一下python和终端的信息交互,和字符串的简单处理.代码如下: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...

  2. PostQueuedCompletionStatus详解

    PostQueuedCompletionStatus函数,向每个工作者线程都发送—个特殊的完成数据包.该函数会指示每个线程都“立即结束并退出”.下面是PostQueuedCompletionStatu ...

  3. Eclipse 安装对 Java 8 的支持

    Java 8 正式版今天已经发布了(详情),但最常用的 Java 开发工具 Eclipse 还没有正式发布对 Java 8 的支持.不过目前可以通过更新 JDT 来支持 Java 8.步骤如下: 菜单 ...

  4. Eclipse设置、调优、使用

    eclipse调优 一般在不对eclipse进行相关设置的时候,使用eclipse总是会觉得启动好慢,用起来好卡,其实只要对eclipse的相关参数进行一些配置,就会有很大的改善. 加快启动速度 1. ...

  5. Server-U与IIS端口占用问题解决

    在新版的ftp软件Server-U(11.X)中,由于其默认设置中监听了80端口,经常会导致IIS不能服务不能正常启用,下面记录如何修改server-u的80端口.     打开Server-U软件, ...

  6. WPF让人哭笑不得的资源(二)

    再吐槽一下(我已经无力吐槽).今天又被资源搞了一天,发现了一个秘密.大家想听就跟随我... 以前写的一个东东,想用mvvm重新实现一下,由于之前的写得很乱,App.xaml里一坨一坨的,就把资源整到一 ...

  7. 鼠标指向GridView某列显示DIV浮动列表

    需求: 当GRIDVIEW数据列过多,不方便全部显示在同一行或者一些子信息需要鼠标指向某关键列GRIDVIEW的时候显示其子信息. 设计:先把需要显示的浮动数据一次过抓取出来.而不是鼠标指向的时候才从 ...

  8. 学习马士兵的struts2/hibernate/spring中遇到的问题及其解决方法

    STRUTS2 1. 写好最简单的hello world项目后,无法通过浏览器访问到hello.jsp页面,提示没有资源. 学习structs2的时间,已经更新到了2.3.16了,structs中的很 ...

  9. SMARTFORM报表程序设计(1)

    SMARTFORM是SAP提供的一款商务单据及报表设置工具,可以在FORM中实现数据的计算及转换等功能,并能在FORM创建的同时生成功能模块,为FORM和ABAP程序提供更为强大的参数接口.输入T-C ...

  10. replace into

    讨人喜欢的 MySQL replace into 用法(insert into 的增强版) 在向表中插入数据的时候,经常遇到这样的情况:1. 首先判断数据是否存在: 2. 如果不存在,则插入:3.如果 ...