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].


题意,一个输入只有一个解,一个元素不能使用两次。

问题转换:在数组中查找一个值,并找到索引

思路:把值理解成key,索引理解成value,就是一个键值对,所以使用哈希表。


class Solution {
public:
    map<int, int> m_map;
    
    vector<int> twoSum(vector<int>& nums, int target) {
        
        vector<int> ans;
        
        for(int i=0; i<nums.size(); i++)
        {
            m_map[ nums[i] ] = i;
        }
        
        for(int i=0; i<nums.size(); i++)
        {
            int need = target - nums[i];
            
            if( m_map.find(need) != m_map.end() && ( m_map[need] != i) )
            {
                ans.push_back(i);
                ans.push_back(m_map[need]);
                break;
            }
        }
        
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/king_qg/article/details/79918541