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

--------------------------------------------------------------------------------------------------------------------------------------------------

1. 暴力搜索,时间复杂度O(n^2),空间复杂度O(1)

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

2.   利用hashtable,其实是c++中的map(由于c++中不存在hash_table,所以没有基于hash_table实现 ),时间复杂度可降至O(nlogn), 但是增加了空间复杂度O(n)

注意的一点是,存入map中的Key 是nums中的值,存入的val是nums中对应的索引。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        int tmp;
        map<int, int> hashtable;
        for (int i = 0; i < nums.size(); i++){
            hashtable[nums[i]] = i;       // 首先循环遍历一次将所有的值存入hashtable中
        }
        for (int i = 0; i < nums.size(); i++){
            tmp = target -  nums[i];
            if (hashtable.find(tmp)!= hashtable.end() && hashtable[tmp]!= i){  // 若是能查找到当前值相对于target的补集
                res.push_back(i);
                res.push_back(hashtable[tmp]);   
                return res;
            }
        }
        
        
    }
};
原文地址:https://www.cnblogs.com/simplepaul/p/7620257.html