【LeetCode】.1.Two Sum
来源:互联网 发布:少林足球 知乎 编辑:程序博客网 时间:2024/06/02 00:34
1. Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
Subscribe to see which companies asked this question
【分析】
分析: 由于输入数组不一定是排序的,如果采用两重循环求解,时间复杂度为:O(n的平方),数据量位置的情况下,这种方式不可取。为了减小时间复杂度,我们可以先将输入数据进行排序,sort()函数的时间复杂度为:O(nlog2n);然后,我们再采用双指针两侧“夹逼”,便可以快速求解。考虑到需要输出的是原数组对应元素下标,排序后下标会改变,因此,我们在排序之前需要对每个元素的值及其下标进行记录,这一点通过结构体可以很容易解决。
【主要知识点】
1.sort()函数的使用,注意对节点型数据(每一个节点包含多个数据)的排序需要一个bool型函数辅助,在本程序中,我们需要对节点中存放的原输入数据(value)进行排序,而不是位置下标(position),因此需要辅助函数cmp。在节点数据只有一个(一般的数组)的情况下,cmp可以缺省,默认升序排列。sort(Array.begin(),Array.end(),cmp),sort()函数前两个参数表示待排序数组的始末位置。
2.双指针“夹逼”法的查找思想
【解法】
struct node{int value;//存放数组元素int position;//存放数组元素对应下表};bool cmp(node a,node b){return a.value<b.value;//按value值,升序排列}class Solution6 {public: vector<int> twoSum(vector<int>& nums, int target) {vector<int> indices;vector<node> Array;//采用vector建立一个节点数组,用于存放输入数组数据及位置(下标)for(int i=0;i<nums.size();i++){node temp;temp.value=nums[i];temp.position=i;Array.push_back(temp);}sort(Array.begin(),Array.end(),cmp);//将节点数组按数据(value)升序排列 unsigned int High,Low;//定义两个指向节点数组两端(首尾)的下标变量High=Array.size()-1;//High节点数组尾端下标Low=0;//节点数组首端下标while(Low<High)//采用两端“夹逼”的方法{while(Low<High&&(Array.at(Low).value+Array.at(High).value>target))High--;while(Low<High&&Array.at(Low).value+Array.at(High).value<target)Low++;if(Array.at(Low).value+Array.at(High).value==target){//找到对应的数据之后,比较其原始下标(position)的大小,从下到大存入indices容器if(Array.at(Low).position>Array.at(High).position){indices.push_back(Array.at(High).position); indices.push_back(Array.at(Low).position);}else{ indices.push_back(Array.at(Low).position); indices.push_back(Array.at(High).position);}return indices;//查询到则返回(默认只有一组合适的数据能满足要求)}}return indices;//未查询到,则返回空 }};
- 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
- 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
- andbase学习笔记六
- alertController和UIAlertView 使用示例
- 【EJB基础】Message Driven Bean
- java.io.EOFException
- dicom协议研究之echo流程分析
- 【LeetCode】.1.Two Sum
- mysql优化-- int类型解析及其优化
- Android View事件机制 21问21答
- 5本最佳的Java面向对象理论和设计模式的书籍
- js时间戳和日期时间格式的互转
- C++课程第一课中出现的问题的探讨
- Github从入门到精髓
- C++ 拷贝构造函数
- C++ 重载输出运算符<<