Array -- Leetcode problem1. Two Sum

  • 描述: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, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

  • 分析:作为leetcode编号为1的题,当然要做一下-_-题目本身非常简单,求出和为target的值的下标。
  • 思路一:用multimap解决。先将数组中的值存入multimap中,然后通过使用迭代器来寻找可以凑成target的两个数,存入vector输出。(9ms)
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> my_vec;
        multimap<int, int> my_map;
        multimap<int , int>::iterator iter;
        multimap<int , int>::iterator iter1;
        for (int i = 0; i < nums.size(); i++) {
            my_map.insert(pair<int, int>(nums[i], i));
        }
        for (iter = my_map.begin(); iter != my_map.end(); iter++) {
            iter1 = my_map.find(target - (iter -> first));
            if (iter1 != my_map.end() && iter1 != iter) {
                my_vec.push_back(iter1 -> second);
                my_vec.push_back(iter -> second);
                my_map.erase(iter -> first);
                my_map.erase((target - (iter -> first)));
                break;
            }
        }
        return my_vec;
    }
};

思路二:使用unordered_map求解,思路和multimap差不多,只是设计更为简介,这种做法不需要存储全部数字,只是在求解的过程中如果找到符合条件的数字就直接进行输出,节省时间和空间。(6ms)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> my_vec;
        unordered_map<int, int> my_map;
        for (int i = 0; i < nums.size(); i++) {
            int need_num = target - nums[i];
            if (my_map.find(need_num) != my_map.end()) {
                my_vec.push_back(my_map[need_num]);
                my_vec.push_back(i);
                break;
            }
            my_map[nums[i]] = i;
        }
        return my_vec;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值