xinyu04

导航

LeetCode Two Sum Map映射

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Solution

不需要 \(O(n^2)\) 的复杂度,我们只需要在扫一遍的过程中,看当前 \(nums[i]\) 对应的 \(target-nums[i]\) 是否在 \(\textbf{Map}\) 中,如果在,则输出;否则将当前的保存

点击查看代码
class Solution {
private:
    map<int,int> idx;
    vector<int> ans;
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int n = nums.size();
        for(int i=0;i<n;i++){
            if(idx.find(target-nums[i])!=idx.end()){
                ans.push_back(i);ans.push_back(idx[target-nums[i]]);
                return ans;
            }
            idx[nums[i]]=i;
        }
        return ans;
    }
};

posted on 2022-07-10 02:25  Blackzxy  阅读(11)  评论(0编辑  收藏  举报