LeetCode 1 Two Sum I
来源:互联网 发布:网络语diss是什么意思 编辑:程序博客网 时间:2024/06/03 21:53
首先想到的是两层遍历法,但是显然时间复杂度太高,是O(N^2),不符合要求,于是就应该想如何降低复杂度,首先想将逐个比较转变为直接查找,即首先计算出 target与当前元素的差,然后在序列中寻找这个差值,这样首先就把问题简化了,而寻找的过程可以先对序列进行快排,然后二分查找,这样整体的复杂度就降低为 O(N*logN) 了;
由于我们最后需要返回的是这些值的索引值,所以查找最快的方法是利用一个 map容器存储每个元素的索引,这样取得某个特定元素的索引只需要常数时间即可完成,将元素及其索引加入map中,其中key对应元素的值,value对应元素的索引。在遍历的过程中进行对应差值的查找,如果找到了就结束遍历,这样时间复杂度最多为 O(N)。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++){
map.put(nums[i], i);
}
for(int i = 0; i < nums.length; i++){
if(map.containsKey(target - nums[i]) && map.get(target - nums[i])!= i){
result[0] = i;
result[1] = map.get(target - nums[i]);
return result;
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
更进一步,如果将两个循环变为一个,即把先构建哈希表变成了后构建,即在每次循环时候去看差值是否存在,如果不存在就将当前元素放入map中。这样当差值存在时即查找成功,输出result。得到:
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
result[1] = i ;
result[0] = map.get(target - nums[i]);
return result;
}
map.put(nums[i], i);
}
return result;
}
}
- LeetCode 1 Two Sum I
- [Leetcode]1(167). Two Sum I, II
- Leetcode 之 Two Sum I
- LeetCode 1 - Two Sum
- leetcode 1 Two Sum
- Leetcode【1】:Two Sum
- [leetcode 1] Two Sum
- 【leetcode-1】Two Sum
- [leetcode 1] Two Sum
- [Leetcode] 1 - Two Sum
- LeetCode (1) Two Sum
- LeetCode 1:《Two Sum》
- LeetCode | #1 Two Sum
- leetcode-1 Two Sum
- Two Sum | LeetCode(1)
- [Leetcode]1Two Sum
- leetcode 1 Two Sum
- leetcode #1 Two Sum
- Python入门之dict和set
- 计算几何【4】精度问题
- 为什么java中不加return在这种情况下不报错并且正常运行
- Start
- mysql--表锁
- LeetCode 1 Two Sum I
- 白+黑(白利用)漏洞加载木马技术解析
- Uncaught TypeError:option dataFormat is not recognized
- c++ primer 第六章总结
- Lintcode:恢复旋转排序数组
- 【XSY1476】平凡之路 斜率优化DP
- GitHub的使用流程、初学者的使用方法
- svm模型训练后的参数说明
- 支付宝