演算法面試通關40講 - 雜湊表/對映

joel-q發表於2024-03-11
1. 兩數之和
#include <iostream>
#include <unordered_map>
using namespace std;
class Solution {
public:
  vector<int> twoSum(vector<int> &nums, int target) {
    vector<int> indices;
    unordered_map<int, decltype(nums.size())> left; // val -> index
    for (decltype(nums.size()) i = 0; i < nums.size(); ++i) {
      auto itr = left.find(target - nums[i]);
      if (itr == left.end()) {
        left[nums[i]] = i;
      } else {
        indices.push_back(itr->second);
        indices.push_back(i);
        break;
      }
    }
    return indices;
  }
};

相關文章