[leetcode]——1.Two Sun

来源:互联网 发布:git 源码安装 编辑:程序博客网 时间:2024/05/23 10:46
思路:最直观的思路是双for循环,时间复杂度为O(n^2)。考虑无序容器,一次遍历即可。每次遍历时在无序容器中查找另一个数,若查找到,两数下标双双压入数组;若没查找到,将当前数和其下标存入无序容器。class Solution {public: vector twoSum(vector& nums, int target) { unordered_maphash; vectort; if(nums.size()<=1) return t; for(int i=0;i<nums.size();++i) { int result=target-nums[i]; if(hash.find(result)!=hash.end()) { t.push_back(hash[result]-1); t.push_back(i); return t; } hash[nums[i]]=i+1; } return t; }};
0 0
原创粉丝点击