zoukankan      html  css  js  c++  java
  • [LeetCode] Two Sum

    算法渣,现实基本都参考或者完全拷贝[戴方勤(soulmachine@gmail.com)]大神的leetcode题解,此处仅作刷题记录。

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int> &numbers, int target) {
     4         unordered_map<int, int> mapping;
     5         vector<int> result;
     6         for (int i = 0; i < numbers.size(); i++) {
     7             mapping[numbers[i]] = i; // 此处存储了位置信息
     8         }
     9 
    10         for (int i = 0; i < numbers.size(); i++) {
    11             const int gap = target - numbers[i];
    12             // 循环,若找到了键且对应的值满足条件,则退出
    13             if (mapping.find(gap) != mapping.end() && mapping[gap] > i) {
    14                 result.push_back(i + 1);
    15                 result.push_back(mapping[gap] + 1);
    16                 break;
    17             }
    18         }
    19         return result;
    20     }
    21 };

    杂记:

    1. Unordered Map

    Internally, the elements in the unordered_map are not sorted in any particular order with respect to either their key ormapped values, but organized into buckets depending on their hash values to allow for fast access to individual elements directly by their key values (with a constant average time complexity on average).

    unordered_map containers are faster than map containers to access individual elements by their key, although they are generally less efficient for range iteration through a subset of their elements.

    2. 成员函数 find

    Searches the container for an element with k as key and returns an iterator to it if found, otherwise it returns an iterator to unordered_map::end (the element past the end of the container).

    注:与[]运算符不同

    3. 存储位置信息尤为重要

    4. 题目明确表示有一个答案,所以不会存在元素重复的情况

  • 相关阅读:
    C# 关键字 virtual、override和new的用法
    架构技术及架构要素总结【转】
    vue文件目录结构
    vue项目中,如何对static文件夹下的静态文件添加时间戳,以达到清除缓存
    webpack中关于require与import的区别
    vue 根据下拉框动态切换form的rule
    el-select 根据value查询其对应的label值
    web前端项目规范
    JavaScript 编码规范
    HTML 编码规范
  • 原文地址:https://www.cnblogs.com/Azurewing/p/4307440.html
Copyright © 2011-2022 走看看