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

Solution:

1. O(n2) runtime, O(1) space – Brute force:

The brute force approach is simple. Loop through each element x and find if there is another value that equals to target – x. As finding another value requires looping through the rest of array, its runtime complexity is O(n2).

2. O(n) runtime, O(n) space – Hash table:

We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.

 public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
int[] result = new int[2];
int length = nums.length;
for (int i = 0; i < length; i++) {
int left = target - nums[i];
if (hm.get(left) != null) {
result[0] = hm.get(left) + 1;
result[1] = i + 1;
} else {
hm.put(nums[i], i);
}
}
return result;
}
}

3. O(nlogn) runtime, O(1) space - Binary search

Similar as solution 1, but use binary search to find index2.

4. O(nlogn) runtime, O(1) space - Two pointers

First, sort the array in ascending order vwhich uses O(nlogn).

Then, right pointer starts from biggest number and left pointer starts from smallest number. If two sum is greater than the target number, move the right pointer. If two sum is smaller than the target number, move the left pointer.

Two Sum 解答的更多相关文章

  1. 3 Sum 解答

    Question Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Fi ...

  2. Combination Sum 解答

    Question Given a set of candidate numbers (C) and a target number (T), find all unique combinations ...

  3. Path Sum 解答

    Question Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that addi ...

  4. Minimum Size Subarray Sum 解答

    Question Given an array of n positive integers and a positive integer s, find the minimal length of ...

  5. C 2015年真题

    1.写出程序输出结果 void main() { char p[10]="abc"; char q[]="xyz"; int i,j; i=0; while(* ...

  6. 【LeetCode题意分析&解答】40. Combination Sum II

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...

  7. Sum Root to Leaf Numbers 解答

    Question Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent ...

  8. 3 Sum Closest 解答

    Question Given an array S of n integers, find three integers in S such that the sum is closest to a ...

  9. Combination Sum II 解答

    Question Given a collection of candidate numbers (C) and a target number (T), find all unique combin ...

随机推荐

  1. 体验Impress.js

    用腻了ppt,prezi的风格看起来更酷一点儿,无意中得知有Impress.js这么一个H5版的prezi,nice,值得一试. 关于Impress.js,网上教程很多,但说实话就跟教小朋友一样,一步 ...

  2. Java中如何分析一个案列---猫狗案例为例

    猫狗案例: 具体事务: 猫.狗 共性: 姓名.年龄.吃饭 分析:从具体到抽象 猫: 姓名.年龄--->成员变量 吃饭       ---> 成员方法 构造方法:无参.有参 狗: 姓名.年龄 ...

  3. NYOJ-520 最大素因子

    这个题基本上就两个知识点, 一个素数筛选法求素数,另一个是求最大公因子, 不过确定最大素数在素数表中的位置时,要用到二分的思想,不然会超时,下面是具体代码的实现; #include <stdio ...

  4. python实现登录函数,比较简单

    一个简单的python实现登录以及修改密码的函数 #密码错误3次,锁定登录: password_list = ['] def account_login(): Tries = 3 while Trie ...

  5. 高健壮性css---Float详细

    (一)关于float 首先我们了解到,CSS网页布局的原理,就是按照HTML代码中对象声明的顺序,以流布局的方式来显示它,而流布局就不得不说到float浮动技术..在HTML中的所有对象,默认分为两种 ...

  6. 初定为EGame

    [Q]在纠结到底要用什么方式写博客,是原生态记录框架编写过程(有点所谓的手把手教学的感觉有木有),还是每个模块整合完毕后写分析文章,新手没有写过博客,不知道那种效果好.朋友们给点建议? 这套框架的初衷 ...

  7. 条件注释判断浏览器版本<!--[if lt IE 9]>(转载)

    <!--[if !IE]><!--> 除IE外都可识别 <!--<![endif]--> <!--[if IE]> 所有的IE可识别 <![ ...

  8. MVC3 展示数据含有html代码处理,配合上篇发布的StringHelper

    @Html.Raw(@StringHelper.SubstringToHTML(Content,30)) StringHelper 地址:http://www.cnblogs.com/Jiawt/p/ ...

  9. trie树信息抽取之中文数字抽取

    这一章讲一下利用trie树对中文数字抽取的算法.trie树是一个非常有用的数据结构,可以应用于大部分文本信息抽取/转换之中,后续会开一个系列,对我在实践中摸索出来的各种抽取算法讲开来.比如中文时间抽取 ...

  10. 【转】C++之内部类(嵌套类)与外部类及友元

    [转]http://baike.baidu.com/link?url=Md223wQoT5s-3cZ5xRnj1pGmvm310DKAuh-HDrcEdc2l24rwobHrdEc_Mi4Z3BGP0 ...