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.

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

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

解析

题目大意:输入一组数据,两个数相加等于特定的target值,返回这两个数的下标(假设只有一个解)
本题目不能用两个指针向中间逼近,因为题目并未说明排序数组,排序后会改变下标

代码

哈希法

  • 时间复杂度:O(n)
  • 空间复杂度:O(n)
  • 用一个哈希map将值与下标映射即可
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        int size=nums.size();
        unordered_map<int,int> m;
        for(int i=0;i<size;i++){
            if(m.find(target-nums[i])!=m.end()){
                res.push_back(i);
                res.push_back(m[target-nums[i]]);
            }
            m[nums[i]]=i;
        }
        return res;
    }
};

评论

暂无评论