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# 中的EventHandler
    Leetcode:Combinations 组合
    Leetcode:Minimum Path Sum
    [LeetCode] Container With Most Water
    一个数n的最少可以由多少个数的平方和组成
    单链表的归并排序
    几个常用的操作系统进程调度算法(转)
    字符串的最长重复子串(转)
    linux静态链接库与动态链接库详解
    简易的hashtable实现
  • 原文地址:https://www.cnblogs.com/Azurewing/p/4307440.html
Copyright © 2011-2022 走看看