【Leetcode】1. Two Sum

Topic address:

https://leetcode.com/problems/two-sum/description/

Topic description:

The first question of leetcode, given a set of integers nums and an integer target, find two numbers from the set, so that the sum of the two numbers is equal to target, return

The indices of these two numbers in the collection. There are two such numbers by default.

solution:

The most violent is the two-layer loop. The approach adopted here is to traverse the set nums. For the current number, if the sum of another number and the current number can be found in the previous number is equal to

target, even if you're done. The processing method uses a set container to record the difference between each previous number and the target, and then only needs to determine whether the current number is in these differences or not.

Code:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        set<int> comp;
        for (size_t i = 0; i != nums.size(); i++) {
            int val = nums.at(i);
            int delta = target - val;
            if (comp.find(val) != comp.end()) {    
                auto it = find(nums.begin(), nums.end(), delta);
                int  first = distance(nums.begin(), it);
                int  second = static_cast<int>(i);
                return {first, second};
            }
            else {
                comp.insert(delta);
            }
        }

        throw::invalid_argument("there is not valid solution");
     }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324609483&siteId=291194637