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. 题目明确表示有一个答案,所以不会存在元素重复的情况

  • 相关阅读:
    Centos 7 zabbix 实战应用
    Centos7 Zabbix添加主机、图形、触发器
    Centos7 Zabbix监控部署
    Centos7 Ntp 时间服务器
    Linux 150命令之查看文件及内容处理命令 cat tac less head tail cut
    Kickstart 安装centos7
    Centos7与Centos6的区别
    Linux 150命令之 文件和目录操作命令 chattr lsattr find
    Linux 发展史与vm安装linux centos 6.9
    Linux介绍
  • 原文地址:https://www.cnblogs.com/Azurewing/p/4307440.html
Copyright © 2011-2022 走看看