Array -- Leetcode problem1. Two Sum

来源:互联网 发布:java遍历list删除元素 编辑:程序博客网 时间:2024/05/01 09:28
  • 描述: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;    }};
原创粉丝点击