【简单】1-两数之和 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.

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

Example1:

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

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

来源:力扣(LeetCode)
难度:简单
链接:https://leetcode-zh.com/problems/two-sum

解题过程

方法一:Hashmap

解题思路

这道题暴力是可以解决问题的,每次固定一个值,检查其后方的值与其相加是否为target即可得到输出结果。但是这样实在太繁琐。

分析遍历过程,其实我们要做的事就是固定一个值,查找与其和为target的值是否在这个数组中,这样就变成了在数组中查找值返回索引的问题了。由此,引入hashmap建立数值-索引的映射关系,此时,每次固定一个值,在hashmap中搜索是否有对应的值作为键即可,此键对应的值就是索引。

注意:题目中提到,不能重复使用同一个值,所以搜索到索引之后一定要检查是不是重复了。

代码

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        map<int, int>check;
        for(int i = 0; i < nums.size(); ++i){
            check[nums[i]] = i;
        }
        for(int i = 0; i < nums.size(); ++i){
            int ind = check.count(target-nums[i]); // count只有0,1两种结果
            if(ind != 0 && check[target-nums[i]] != i){ // 一个元素不可以利用多次
                res.push_back(i);
                res.push_back(check[target-nums[i]]);
                break;
            }
        }
        return res;
    }
};

方法二:vector.find()

思路

同样是前一种方法的思想,既然想要查找后面有没有对应的元素,那直接使用vector容器的find函数就可以找到我们要的索引了,而且find函数可以指定搜索的起点,我们将搜索的起点定在当前固定值的下一位,就可以避免题目中提到的重复利用同一个元素了。

代码

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        int size = nums.size();
        if(size == 0){
            return res;
        }
        for(int i = 0; i < size; ++i){
            vector<int>::iterator result = find(nums.begin()+i+1, nums.end(), target-nums[i]); // 从下一位开始搜索
            if(result != nums.end()){
                res.push_back(i);
                res.push_back(result-nums.begin());
                break;
            }
        }
        return res;
    }
};

总结

  1. 两种算法的空间消耗都很差不多,hashmap用了8.6M,vector.find()用了7.6M;但是从运行时间上来看vector用时716ms远超过hashmap的24ms;

  2. 这道题的一个关键点就在于保存索引-数值之间的映射关系,由此应该直接联想到map容器;

  3. 本题在描述上有一点模糊,只说了不可以重复利用同一个值,却没有说明数组中有重复元素时应该怎么处理,当输入为[2,2,2,4,6] 4时,输出为[0,2];当输入为[3,3,3,4,2] 6时,输出为[3,4],但是上述两种方法仍旧通过了。

posted @ 2020-04-09 21:05  陌良  阅读(158)  评论(0编辑  收藏  举报