leetcode-哈希表-1.两数之和

//C++
/**
 * Two Sum
 * 两数之和
*/

class Solution 
{
public:
    
    //
    // The implementation as below is bit tricky. but not difficult to understand
    //
    //  1) Traverse the array one by one
    //  2) just put the `target - num[i]`(not `num[i]`) into the map
    //     so, when we checking the next num[i], if we found it is exisited in the map.
    //     which means we found the second one.
    //      
    vector<int> twoSum(vector<int> &numbers, int target) 
{
        unordered_map<int, int> m;
        vector<int> result;
        for(int i=0; i<numbers.size(); i++)
{
            // not found the second one
            if (m.find(numbers[i])==m.end() )
 { 
                // store the first one poisition into the second one's key
                m[target - numbers[i]] = i; 
            }
            else 
            { 
                // found the second one
                result.push_back(m[numbers[i]]+1);
                result.push_back(i+1);
                break;
            }
        }
        return result;
    }
};
//Python
/**
 * Two Sum
 * 两数之和
*/

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}
        for i, num in enumerate(nums):
            if target - num in d:
                return [d[target - num], i]
            d[num] = i
            

猜你喜欢

转载自blog.csdn.net/qq_32391345/article/details/106817752