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.

最新文章

  1. RabbitMQ consumer的一些坑
  2. django 1.7之后python manage.py syncdb没有了
  3. 图片上传安全性问题,根据ContentType (MIME) 判断其实不准确、不安全
  4. 机器学习中的Bias(偏差),Error(误差),和Variance(方差)有什么区别和联系?
  5. Python中下划线的使用方法
  6. [Reship]如何回复审稿人意见
  7. [Educational Codeforces Round 16]B. Optimal Point on a Line
  8. 鼠标经过容器放大--css3
  9. java工具类系列 (四.SerializationUtils)
  10. javascript实现数据结构:广义表
  11. CentOS 在同一窗口打开文件夹
  12. spring boot oauth2的一些记录
  13. tomcat部署服务乱码问题
  14. Android源代码编译过程及指令
  15. hybrid App cordova打包webapp PhoneGap
  16. Python直接控制鼠标键盘
  17. 【Linux】-NO.86.Linux.6.C.1.001-【CentOS 7 Install GCC】-
  18. 使用Dockerfile创建支持SSH服务的镜像
  19. ESXi虚拟机开机进入bios的方法
  20. 谈论linux同组多用户操作问题

热门文章

  1. 《Android开发艺术探索》读书笔记 (10) 第10章 Android的消息机制
  2. Android Studio 快捷键(转)
  3. Git和Github的应用与命令方法总结
  4. CSS3简单的空调
  5. H5移动端的注意细节
  6. [置顶] Spring的DI依赖实现分析
  7. ubantu-命令-进入超级用户
  8. underscorejs-pluck学习
  9. 个人Python常用Package及其安装
  10. UVA - 1614 Hell on the Market(贪心)