1. Two Sum
来源:互联网 发布:js div 编辑:程序博客网 时间:2024/05/12 12:07
问题:
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
分析:
方法1 - 最直接的方法可以用穷举:用两个for循环来测试得到的组合是否符合要求。会超时!(O(n^2), O(1))
方法2 - 逐个计算每个数组元素要的到target需要加上的那个数,再扫描数组中是否出现这个数。并没有任何改进。估计也会超时。(O(n^2), O(1))
方法3 - 思路来自于方法2,对于检查存在性的问题HashMap、HashSet是最能优化时间复杂度的。用HashMap改进方法2。(O(n), O(n))
代码:
public class Solution { public int[] twoSum(int[] numbers, int target) { Map<Integer, Integer> helper = new HashMap<Integer, Integer>(); for(int i=0; i<numbers.length; i++){ if(helper.containsKey(numbers[i])){ return new int[]{helper.get(numbers[i]).intValue() + 1, i + 1}; } helper.put(new Integer(target - numbers[i]), new Integer(i)); } return null; }}
0 0
- 1. Two Sum && 167. Two Sum II
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1. Two Sum
- 1. Two Sum Ruby
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1.Two Sum
- C++中字符型变量的地址输出
- 腾讯历年笔试题(计算机基础)
- MySQL性能优化的最佳20+套经验
- using 的范围用法
- Bootstrap 分页插件的使用
- 1. Two Sum
- [LeetCode] Valid Sudoku
- 图像有用区域 bfs
- 自学Swift-UIKit
- java语言实现创建型设计模式—创建者模式
- jquery实现多余文字显示或隐藏
- virtualbox中centos装VBOXADDITIONS的注意事项
- p123 36
- c++模板详解(一)