leetcode001 Two Sum

来源:互联网 发布:济南软件测试培训 编辑:程序博客网 时间:2024/05/29 23:23

一开始想用头部一个指针尾部一个指针的思路来做。后来看了网上的攻略才发现数组是乱序的。网上的思路比较巧妙,用了一个hashmap,其中key值为数组的value,value值为数据的index,查找的复杂度为O(N)


代码如下:

vector<int> twoSum(vector<int>& nums, int target) {    vector<int> ret;    map<int,int> m;    for(int i=0;i<nums.size();i++)    {        int key = target - nums[i];        if(m.find(key) == m.end()){           m[nums[i]] = i;      }     else{ret.push_back(m[key]+1);ret.push_back(i+1);break;      }}return ret;}


0 0
原创粉丝点击