1. Two Sum(Leetcode每日一题-2020.10.03)

    科技2024-12-23  10

    Problem

    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.

    Constraints:

    2 <= nums.length <= 105-109 <= nums[i] <= 109-109 <= target <= 109Only one valid answer exists.

    Example1

    Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1].

    Example2

    Input: nums = [3,2,4], target = 6 Output: [1,2]

    Example3

    Input: nums = [3,3], target = 6 Output: [0,1]

    Solution

    class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> ret; unordered_map<int,int> my_map; for(int i = 0;i<nums.size();++i) { int num_to_find = target - nums[i]; if(my_map.count(num_to_find)) { ret.push_back(i); ret.push_back(my_map[num_to_find]); return ret; } my_map[nums[i]] = i; } return ret; } };
    Processed: 0.034, SQL: 8