题目:两数之和(C++)

方法1:暴力遍历(时间复杂度O(n^2),空间复杂度O(1))

vector<int> twoSum(vector<int>& nums, int target) 
{
    int arraySize = nums.size();
    for (int i = 0; i < arraySize; ++i)
        for (int j = arraySize - 1; j > i; --j)
            if (nums[i] + nums[j] == target)
                return move(vector<int>{i, j});
    return move(vector<int>{ });
}

在此之后本想用快速排序的方法查找,但是看到题目要求输出的是数组下标,这样排序时就需要保存原来的下标。与其这样排序不如之间用map来做。

之后看了看速度最快的方法,然后得出方法2如下。

 1 static const auto io_speed_up = []()
 2 {
 3     std::ios::sync_with_stdio(false);//取消C++与C语言的缓冲区保护,加快执行速度
 4     cin.tie(nullptr);//取消cin每次输入时对缓冲区的刷新,加快执行速度
 5     return 0;
 6 }();
 7 
 8 class Solution {
 9 public:
10     vector<int> twoSum(vector<int>& nums, int target) {
11         int size = nums.size();
12         unordered_map<int,int> hashTable;
13         for (int i = 0; i < size; ++i) 
14         {
15             int complement = target - nums[i];
16             auto found = hashTable.find(complement);
17             if (found == hashTable.end())//使用pair对map进行插入快于map直接插入
18             {
19                 pair<int, int> p(nums[i],i);
20                 hashTable.insert(p);
21             }
22             else
23                 return move(vector<int>{ found->second, i });
24         }
25         return move(vector<int>{ });
26     }
27 };

其中设置了一个静态lambda表达式,该表达式会在程序最开始执行,加快leetcode中数据的导入速度。

然后在map使用了unordered_map,该map会加快访问速度但是减慢遍历速度(刚好适合该题)。

之后用pair插入map(该方法快于别的插入map的方法)。

猜你喜欢

转载自www.cnblogs.com/change4587/p/9142837.html
今日推荐