LeetCode Two Sum
来源:互联网 发布:mac地址采集摄像机 编辑:程序博客网 时间:2024/06/01 10:34
问题描述:https://leetcode.com/problems/two-sum/
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
首先,根据题目给出的例子,大家一般都会想到利用两个头尾指针的方式进行运算。方法在于index1指向vector[0],index2指向vector[size()-1],然后计算Index1和index2所指的数值之和,如果和大于target,证明需要讲index2--,反之需要将index1++,如果想等,则直接返回index1和index2即可。
但是测试数据却不是完全有序的,刚开始我以为LeetCode并没有包含algorithm头文件,所以使用选择插入排序进行vector排序,时间复杂度为O(n2),提交之后超时了。后来才知道,原来LeetCode已经包含了algorithm头文件,所以该用sort函数完成vector的排序,时间复杂度为O(nlogn)。
由于题目要求输出的是原先列的索引,所以我们需要复制一个新的vector,对新的vector进行排序,在新的vector寻找和等于target的两个元素,然后在原先的vector中查找这两个元素,代码如下:
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> tempv(nums);sort(tempv.begin(), tempv.end());int index1 = 0, index2 = tempv.size()-1;while (tempv[index1]+tempv[index2]!=target){if (tempv[index1] + tempv[index2] < target)index1++;elseindex2--;}int start = tempv[index1], end = tempv[index2];int i = 0;while (nums[i] != start){i++;}vector<int> rs;start=i+1;i = nums.size() - 1;while (nums[i] != end)i--;end=i+1;rs.push_back(start<end?start:end);rs.push_back(start<end?end:start);return rs; }};
- 【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
- LightOJ 1011 Marriage Ceremonies【状压DP】
- iOS中图片拉伸技巧
- 用Js的eval解析JSON中的注意点
- LightOJ 1074 – Extended Traffic 【SPFA判负环】
- 在使用Word 2010办公软件的过程中,我们经常会遇到空白页,对此我整理了一篇删除空白页的方法汇总,希望对大家有帮助
- LeetCode Two Sum
- hdu 5202 Rikka with string
- 如何交换权重为0的网站友情链接
- 单引号和双引号同时使用时注意
- NYOJ 524 A-B Problem(大数是否相等)
- spring框架面试相关问题
- 一行Python代码——单词逆转
- srm 533
- 假设检验