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. iOS iOS8新特性--UIPopoverPresentationController

    1.回顾UIPopoverController的使用,下面这份代码只能在ipad下运行 // 初始化控制器,SecondViewController类继承自UIViewController Secon ...

  2. iOS异步图片加载优化与常用开源库分析

    网络图片显示大体步骤: 1.下载图片: 2.图片处理(裁剪,边框等): 3.写入磁盘: 4.从磁盘读取数据到内核缓冲区: 5.从内核缓冲区复制到用户空间(内存级别拷贝): 6.解压缩为位图(耗cpu较 ...

  3. IOS 开发 【os x 使用常识】

    开始看<learn Objective-C on the Mac>这本书,很基础,准备快速看完. 刚接触mac 的 os x 系统,很不适应,介绍一点我刚学的基本常识. 1.os x 显示 ...

  4. 鼠标滑动判断与y轴的距离

     $(window).scroll(function(){                        var y = window.scrollY;//754到达                  ...

  5. UITabBarController自定义一

    UITabBarController自定义一 首先在Appdelegate.m文件中将UITabBarController的子类设置为rootViewController,并设置其viewContro ...

  6. unexpected nil window in _UIApplicationHandleEventFromQueueEvent...

    unexpected nil window in _UIApplicationHandleEventFromQueueEvent, _windowServerHitTestWindow: <UI ...

  7. AFN发送请求失败

    发送请求出现这个错误 Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Coc ...

  8. python正则表达式之使用规则

         正则表达式在我看来是提供一个模板,将待匹配的字符串与模板匹配,匹配不到则返回为空,匹配成功根据需要返回匹配的字符串. 正则表达式比字符串本身的功能要强一点,当然性能上略有不如. 我们使用正则 ...

  9. 你好,C++(7)第三部分 C++世界众生相 3.2.1 变量的定义与初始化

    第3部分 C++世界众生相 在听过了HelloWorld.exe的自我介绍,完成了与C++世界的第一次亲密接触后,大家是不是都急不可待地想要一试身手,开始编写C++程序了呢?程序的两大任务是描述数据和 ...

  10. Android动画 fillAfter和fillBefore

    fillBefore是指动画结束时画面停留在此动画的第一帧; fillAfter是指动画结束是画面停留在此动画的最后一帧. java代码设置如下: /*****动画结束时,停留在最后一帧******* ...