leetcode--Two Sum
来源:互联网 发布:淘宝助理5.7 编辑:程序博客网 时间:2024/05/29 17:04
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
题意:给你一个数组和一个target,在数组中找出两个和为target的整数。
返回这两个整数的index,并且要求index1小于index2
注意,index是基于1开始的,也就是说数组的第一个index是1,而不是0
分类:数组,Hash
解法1:由于数组是无序的,容易想到的方法就是排序以后,从头尾开始找。
排序以后,我们要记录原来元素在数组中的位置,所以创建了一个类用于记录。
在Java里面我们要实现自己的比较器就可以了。排序算法的时间复杂度是O(nlogn)。
排序以后从头尾开始找,如果头尾和比target大,说明尾要减小。如果比target小,说明头要增大。
直到找到为止,时间复杂度是O(n)
所以总的时间复杂度是O(nlogn)
解法二:使用HashMap来记录元素所在的位置。
遍历数组,对于当前元素cur,用target减去cur,然后判断这个差值在hashMap中能不能找到。
如果找不到,先将cur和其index存入map
接着判断下一个元素。
原文链接http://blog.csdn.net/crazy__chen/article/details/45441671
- 【Leetcode】Two Sum (Sum)
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- [LeetCode]Two Sum
- leetcode Two Sum
- [Leetcode] Two Sum
- [leetcode] Two Sum
- LeetCode - Two Sum
- leetcode之Two Sum
- LeetCode | Two Sum
- 递归问题学习二之卡牌组合问题
- CSS 外边距合并
- URL发送post请求
- 工具类Date SimpleDateFormat Canlendar
- 存储过程
- leetcode--Two Sum
- Total Commander之添加两边同时进行文件夹切换操作
- 【思维】hdu 6060 RXD and dividing
- C++工程中使用caffe
- leetcode--Add Two Numbers
- 第一章课后的几个编程题——数据结构与问题描述Java语言描述(第3版)
- Java 中的堆和栈
- color/box-flex/transition/inline-block/outline/:not()
- dapper-fastcrud