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

第一反应可以把nums循环两次,用n^2的时间复杂度

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

后来想到可以把每个数字放到Map里,总的时间复杂度可以到n。

class Solution{
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        map<int, int> mymap;
        int n = numbers.size();
        vector<int> ans;
        for(int i=0;i<n;i++){
            int t = target - numbers[i];
            if(mymap.count(t) > 0){
                ans.push_back(mymap[t]);
                ans.push_back(i);
                return ans;
            }else{
                mymap[numbers[i]] = i;
            }
        }
        return ans;
    }
};

上面程序的运行时间是9ms,打败了54.67% 。

后来看了前排6ms的代码,发现只是把map换成了unordered_map,因为map是红黑树实现的,会根据键的大小排序,查找的时间复杂度是n,而unorder_map没有排序,是hash实现的,查找的时间复杂度是常数级,因此会更快。

转载请保留原文链接及作者
本文标题:
文章作者: LepeCoder
发布时间:
原始链接:
原文地址:https://www.cnblogs.com/lepeCoder/p/7230550.html