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

 题目大意:给一串整形数组和一个整数,返回两个数下标,它们的和为给定的整数。保证只有一种,并且不能使用同一个数两次。

①暴力求解

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        for(int i = 0; i < nums.size(); i++){
            for(int j = i+1; j < nums.size(); j++){
                if((nums[i] + nums[j]) == target){
                    result.push_back(i);
                    result.push_back(j);
                    return result;
                }
            }
        }
        return result;
    }
};

  • 时间复杂度为O(n^2)

②用哈希表存,用空间换时间,只遍历一个数,剩下的把target减去这个得到,再判断它在Hash表里是否存在。时间复杂度为O(n)

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


猜你喜欢

转载自blog.csdn.net/qq_33655674/article/details/81053194