[leetcode]1.Two Sum
来源:互联网 发布:csgo数据互换器永久 编辑:程序博客网 时间:2024/06/05 19:11
题目链接: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
思路:
第一种:两重循环搜索所有的情况,时间复杂度是O(n*n),估计是过不了测试数据的。
第二种:将数组排序,然后两个指针从左右分别扫描数组:
1)如果当前和大于target,则右指针左移一位;
2)如果当前和小于target,则左指针右移一位
这种方法需要排序和记录原数组中数的坐标,并且得到的index仍然需要排序放入结果中。时间复杂度是O(n*log(n)),这是排序的复杂度。
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { if(nums.size() < 2) return {}; vector<pair<int,int>> vec; for(int i = 0;i < nums.size();i++) vec.push_back(make_pair(nums[i],i)); sort(vec.begin(),vec.end()); int left = 0,right = nums.size()-1; while(left < right){ int val = vec[left].first + vec[right].first; if(val == target) return vector<int>{vec[left].second,vec[right].second}; else if(val > target) right--; else left++; } return {}; }};
第三种:将原数组中的数放到hash表中,然后扫描一遍即可,很方便。时间复杂度为O(n). 这种方法有一个限制就是不能有重复解.还有注意的是如果一个数可以分解为两个相同数的和的情况。
class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int,int> hash; for(int i=0;i<nums.size();i++) hash[nums[i]]=i; for(int i=0;i<nums.size();i++) if(hash.count(target-nums[i])&&hash[target-nums[i]]!=i) return vector<int>{i,hash[target-nums[i]]}; return vector<int>(0); }};
- 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
- PitchBook:2017年Q3 Uber亏损14.6亿美元
- JavaScript基础(9.左侧菜单实例)
- strlen和sizeof
- MySQL死锁--Innodb行锁
- android面试题总结
- [leetcode]1.Two Sum
- 贝塞尔曲线——cubic-bezier详解
- 2017年全球人工智能研究高校数据解读
- IDC:预计2018年全球物联网(IoT)支出金额7725亿美元
- 使用SSH2,登录后刷新首页,会出现偶数次正常奇数次失败
- Base64、32、16 编码解析
- 探索Oracle之数据库升级二 11.2.0.3升级到11.2.0.4完整步骤--测试成功版本
- 51Nod 1097 拼成最小的数 排序
- 北斗GPS两系统实现兼容互操作 提升导航定位精度