欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

1. Two Sum

程序员文章站 2024-02-17 12:25:46
...

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

我的解法

时间:14%
空间:60%

主要慢的原因:
for循环不适用于大型数据,比较慢,使用哈希表来查找可以显著提高程序运行速度

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

推荐解法

速度:97.81%
空间:12.60%

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