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

# LeetCode 答案

程序员文章站 2022-03-15 20:36:05
...

记录一个C++小白的刷题辛酸泪. 以及感谢我的猴不辞辛劳地为我讲解各种数据结构和提供解答.

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.
Examples:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Language: cpp

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

知识点:

  1. unordered_map: unordered_map和map类似,都是存储的key-value的值,可以通过key快速索引到value. map的内部数据结构为红黑树,map中的元素是按照二叉搜索树存储的, 因此map中的元素都是有序的, 时间复杂度为O(logN). unordered_map采用哈希表, 时间复杂度为O(1).
  2. return {}