Two sum(在数组中找两个数,使其和为指定值)
2015-05-31 17:08
393 查看
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
Hide Tags
Array Hash
Table
Solutions:
1)最直接的O(N^2)的算法,再leetCode上超时。
2)先将数组排序,再从两端向中间查找,因为有可能有相等的元素,所以找第二个数的位置时要从高端开始。
3)用一个map<int, int>存储已经遍历过的数,键为数,值为位置(从1开始)。遍历到某数x,若target-x已经被遍历过,则此2数即为所求。
但其时间反而比上面的要长。
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
Hide Tags
Array Hash
Table
Solutions:
1)最直接的O(N^2)的算法,再leetCode上超时。
2)先将数组排序,再从两端向中间查找,因为有可能有相等的元素,所以找第二个数的位置时要从高端开始。
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> v=nums; sort(v.begin(), v.end()); int l=0, r=v.size()-1; while(l<r){ if(v[l]+v[r]>target) { --r; } else if(v[l]+v[r]<target) { ++l; } else{ break; } } int i=0; for(i=0; i<nums.size(); ++i) { if(nums[i] == v[l]) { l=i+1; break; } } for(i=nums.size()-1; i>=0; --i) { if(nums[i] == v[r]) { r=i+1; break; } } vector<int> ret; if(l>r){ swap(l, r); } ret.push_back(l); ret.push_back(r); return ret; } };
3)用一个map<int, int>存储已经遍历过的数,键为数,值为位置(从1开始)。遍历到某数x,若target-x已经被遍历过,则此2数即为所求。
但其时间反而比上面的要长。
class Solution{ public: vector<int> twoSum(vector<int> &nums, int target) { map<int, int> m; int l=0, r=0; for(l=0; l<nums.size(); ++l) { if((r=m[target- nums[l]]) != 0) { break; } m[nums[l]]=l+1; } l+=1; if(l>r) { swap(l, r); } vector<int> ret; ret.push_back(l); ret.push_back(r); return ret; } };
相关文章推荐
- 生产者消费者模式引子
- Android FragmentPagerAdapter 数据刷新问题
- HDU 2020 绝对值排序
- android网址
- Python快速入门(1)
- PHP foreach()语句的一个诡异问题
- 查找最小的k个元素(堆处理和非堆处理)
- 第12周项目2 - 摩托车继承自行车和机动车
- 高并发服务器学习之原子性
- 【转】Linux下Android ADB驱动安装详解
- [LeetCode][JavaScript]Longest Consecutive Sequence
- 判断整数序列是不是二元查找树的后序遍历结果
- HDU 2019 数列有序!
- JAVA 继承 extends
- c(API) 对文件内容的增删查改
- 第12周项目1- 教师兼干部类
- 不要去放水
- 输出一个字符串的全排列
- Internal Sorting: Distribution counting: Sorting by counting
- Android 坐标与宽高研究getLeft() getTop() getRight()和getBottom()