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