LeetCode.1 (sum of two numbers)-simple

LeetCode.1 (sum of two numbers)-simple

  • Given an integer array nums and a target value target, please find the two integers whose sum is the target value in the array, and return their array index. You can assume that each input will only correspond to one answer. However, the same element in the array cannot be used twice.

    Examples:

    给定 nums = [2, 7, 11, 15], target = 9
    
    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]
    
  • Code:

    //2020_04_17
    class Solution
    {
    public:
        vector<int> twoSum(vector<int> &nums, int target)
        {
            vector<int> res{0, 0};                //结果容器
            unordered_map<int, int> um;           //哈希表(值,下标)
            for (int i = 0; i < nums.size(); i++) //遍历容器元素
            {
                auto it = um.find(target - nums[i]); //查找另一个元素
                if (it != um.end())                  //如果找到
                {
                    res[0] = it->second; //输出其下标
                    res[1] = i;          //输出当前遍历的元素下标
                    return res;          //返回
                }
                um[nums[i]] = i; //没找到则将该元素加入哈希表
            }
            return res;
        }
    };
    
  • result:

Guess you like

Origin www.cnblogs.com/iceix/p/12717215.html