leetcode--1. 两数之和--用map

103 篇文章 0 订阅
99 篇文章 0 订阅

题目描述:

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

代码如下:

C++

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
         //不能排序
         //存在乱序;
         int i = 0;
         vector<int> res;
         multimap<int, size_t> find_location;
         multiset<int> item(nums.cbegin(), nums.cend());
        for (auto &r : nums) {
	            find_location.insert(make_pair(r, i));
	            i++;
        }
        auto k = 0;
        auto map_it = find_location.cbegin();
        while (map_it != find_location.end()) {//遍历map中的所有成员;
                k = target - map_it->first;//目标值与成员值相减;
               // cout<<"map_it->first:"<<map_it->first<<endl;
                if(k!= map_it->first){//当时两个不同的元素相加得到目标数时:
                       cout<<"2"<<endl;
	                   if (item.find(k) != item.end()) {//相减的结果是否存在于上述数组中
		               auto y = find_location.find(map_it->first)->second;
		               auto x = find_location.find(k)->second;
		               res.push_back(y);
		               res.push_back(x);
		               return res;
	                   }
                }
                else{//当两个相同元素相加得到目标数时:
                       cout<<"1"<<endl;
                       auto y = find_location.find(map_it->first)->second;
                       multimap<int,size_t>::iterator end;
                       end = find_location.upper_bound(k);
                       --end;
                       auto x=(end)->second;
                       res.push_back(y);
		               res.push_back(x);
		               return res;
               }
               ++map_it;
       } 
    }
};

//几个cout语句是用作调试的;

//主要方法是采用了C++的STL库中的multimap和multiset函数,因为之前没怎么用过,查阅了半天的资料才弄出来。。目前没想到别的方法。。

//还有就是在使用迭代器的时候忘了++,要记住。

//结果截图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值