[Array]Two Sum
2016-07-02 21:45
399 查看
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
首先对数组进行排序,然后遍历数组,即针对每一个元素,寻找(target-nums[i]), 寻找的方法采用二分法。这样空间复杂度为O(n)(用来记录下标),排序时间复杂度为O(nlogn),遍历数组进行二分查找时间复杂度为O(nlogn)。
另外一种想法是利用map,大致思路是遍历一遍数组,将已经访问过的元素存入到map中,再利用value = target - 正在访问的元素,然后回到map中进行查找value。
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
首先对数组进行排序,然后遍历数组,即针对每一个元素,寻找(target-nums[i]), 寻找的方法采用二分法。这样空间复杂度为O(n)(用来记录下标),排序时间复杂度为O(nlogn),遍历数组进行二分查找时间复杂度为O(nlogn)。
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> res; vector<int> map(nums); sort(nums.begin(),nums.end()); for(int i = 0;i < nums.size();i++){ int value = target - nums[i]; int left=i+1,right=nums.size()-1; while(left<=right){ int middle = (left+right)/2; if(nums[middle]==value){ for(int j=0;j<map.size();j++){ if(map[j]==nums[i]||map[j]==value) res.push_back(j); } break; } if(value<nums[middle]){ right = middle-1; } else left = middle+1; } if(!res.empty()) break; } return res; } };
另外一种想法是利用map,大致思路是遍历一遍数组,将已经访问过的元素存入到map中,再利用value = target - 正在访问的元素,然后回到map中进行查找value。
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> res; map<int,int> mp; map<int,int>::iterator it; for(int i=0;i<nums.size();i++){ int find_number = target - nums[i]; it = mp.find(find_number); if(it!=mp.end()){ res.push_back(it->second); res.push_back(i); break; } mp[nums[i]]=i; } return res; } };
相关文章推荐
- Codeforces Round #360 (Div. 2) C D E
- [Array]Two Sum
- jquery onready的问题
- jquery遍历数组的问题
- 【JavaWeb开发】Eclipse或MyEclipse配置Tomcat
- vs2008调试 Release(链接器来生成调试信息)
- 尝试一下: 仅加密已用磁盘空间
- 可能是讲解Android事件分发最好的文章
- 中国剩余定理
- Python开发的10个小贴士
- C++ DLL导出函数的两种方法(导出序号那种方法,别人看不到函数名)
- firstChild,nextSibling,childNodes等属性的问题
- 【HTML】HTML详解——标签
- 判断number时最好用正则
- SimpleDateFormat和Locale.getDefault()的用法
- 进程序名得到进程ID和句柄与进程的公司名(使用快照和GetPeFileCompany和VerQueryValueW等函数)
- 在Linux上以服务的方式运行ASP.NET Core站点
- DialogFragment的使用与底层绘制
- 可以直接获取id对象
- vitamio5.x的简单使用