Two Sum 解答
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 解答的更多相关文章
- 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 ...
- Combination Sum 解答
Question Given a set of candidate numbers (C) and a target number (T), find all unique combinations ...
- Path Sum 解答
Question Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that addi ...
- Minimum Size Subarray Sum 解答
Question Given an array of n positive integers and a positive integer s, find the minimal length of ...
- C 2015年真题
1.写出程序输出结果 void main() { char p[10]="abc"; char q[]="xyz"; int i,j; i=0; while(* ...
- 【LeetCode题意分析&解答】40. Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...
- Sum Root to Leaf Numbers 解答
Question Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent ...
- 3 Sum Closest 解答
Question Given an array S of n integers, find three integers in S such that the sum is closest to a ...
- Combination Sum II 解答
Question Given a collection of candidate numbers (C) and a target number (T), find all unique combin ...
随机推荐
- 《Android开发艺术探索》读书笔记 (4) 第4章 View的工作原理
本节和<Android群英传>中的第3章Android控件架构与自定义控件详解有关系,建议先阅读该章的总结 第4章 View的工作原理 4.1 初始ViewRoot和DecorView ( ...
- warning : json_decode(): option JSON_BIGINT_AS_STRING not implemented in xxx
先来一段json_decode官方说明 mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, i ...
- 【小TIP】记录各种错误【更新中】
最好程序一遍通过,为了提高代码能力,这里将用TIP的形式记录来犯过的错误.不断更新中. *已经转移到闪存.. [150214]WA:检查是否数组开小了. [150212]WA:如果程序中有乘号,需要留 ...
- codevs 1725 探险 (二分)
/* 二分答案 这个题目要求“体力和最小的那个小组的所有人的体力和尽量大” 很明显我们二分最小体力 如果合法 逐渐放大 但是这里我们二分的是最小而不是最大 所以累加的体力>=ans时 跳过当前体 ...
- HttpClient 发送图片
var httpClient = new HttpClient(); using (FileStream fs = new FileStream("C:\\1.jpg", File ...
- MemCachedClient数据写入的三个方法
set方法 1 将数据保存到cache服务器,如果保存成功则返回true 2 如果cache服务器存在同样的key,则替换之 3 set有5个重载方法,key和value是必须的参数,还有过期时间,h ...
- Android开发手记(24) Log的使用及颜色的更改
在程序开发过程中,LOG是广泛使用的用来记录程序执行过程的机制,它既可以用于程序调试,也可以用于产品运营中的事件记录.在Android系统中,提供了简单.便利的LOG机制,开发人员可以方便地使用.本文 ...
- MD5算法的使用
using System.Security.Cryptography; using System.Text; StringBuilder sb = new StringBuilder();//构建一个 ...
- 巧妙的Jq仿QQ游戏导航界面学习
先贴上源代码 <!doctype html> <html> <head> <meta charset="utf-8"> <ti ...
- Xcode7 通过 Single View Application 得到一个 Empty Application 工程
方法: 创建一个 Empty Application 工程 下面还是详细的说一下通过一个 Single View Application 工程得到一个 Empty Application 工程的方法: ...