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. C# 读取XML文件示例

    有关XML文件编写规范,请参考:http://www.w3school.com.cn/xml/index.aspXML内容如下(文件名为:Information.xml):浏览器显示: <?xm ...

  2. CentOS下FTP服务器安装与配置

    安装vsftpd yum install vsftpd 启动/重启/关闭vsftpd服务器 CentOS7 以下: 启动: service vsftpd start 停止: service vsftp ...

  3. Python之路,Day26-----暂无正在更新中

    Python之路,Day26-----暂无正在更新中

  4. VB 生成xml文件 并使用xsd验证

    最近客户的一个需要,要求将数据以xml的形式发送. vb 实现代码 Private Function createXML_old(ByVal xmlName As String) As Boolean ...

  5. SQL Server强制删除发布

    今日发现SQL Server 中 存在以前(系统还原前)的发布内容,使用鼠标->右键,选择删除,失败.   可使用语句: EXEC SP_REMOVEDBREPLICATION '发布数据库名称 ...

  6. Sublime Text3使用详解

    Sublime Text简介 Sublime Text - 性感的代码编辑器.程序员之必备神器 Sublime Text 是一个代码编辑器,也是HTML和散文先进的文本编辑器.Sublime Text ...

  7. 生成package.json和bower.json

    1.安装nodejs 2.安装bower工具   cmd:npm bower install 3.生成package.json  cmd:npm init 4.生成bower.json cmd:bow ...

  8. 【USACO 1.5.3】特殊的质数肋骨

    [题目描述]农民约翰的母牛总是生产出最好的肋骨.你能通过农民约翰和美国农业部标记在每根肋骨上的数字认出它们. 农民约翰确定他卖给买方的是真正的质数肋骨,是因为从右边开始切下肋骨,每次还剩下的肋骨上的数 ...

  9. BAT清理垃圾

    @echo off title ϵͳȥm del /f /s /q %systemdrive%\*.tmp del /f /s /q %systemdrive%\*._mp del /f /s /q ...

  10. 插入数据前设置字符编码为utf8

    xxx.php保存时选择utf8编码,页头最好加上 header('conten-type:text/html;charset=utf-8'); 在执行CRUD操作前先执行一下 mysql_query ...