1 Two Sum(Medium)

1.题目要求在给定的数组和target中,找出数组中的两个数a和b,使得a+b=target
2.遍历一次nums,利用map记录已经遍历过的nums[i],并记录其index :i+1
3.每次求出b=target-nums[i],检测b是否在map中,如果在,则已经得到答案,否则,把nums[i]存到map里面

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

Subscribe to see which companies asked this question

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int,int> exist;
        vector<int> ans(0);
        for(int i=0;i<nums.size();i++)
        {
            int b=target-nums[i];
            if(exist.find(b)!=exist.end())
            {//如果哈希表里面已经存在b,则压入ans中,并return,b先于nums[i]放入哈希表,所以b的index肯定小于nums[i]
                ans.push_back(exist[b]);
                ans.push_back(i+1);
                return ans;
            }
            else
            {//找不到,即和不为target,则把nums[i]放入哈希表
                exist[nums[i]]=i+1;
            }
        }

    }
};

发表评论

电子邮件地址不会被公开。 必填项已用*标注