Files
cpp-flashcards/inbox.org
T
tomatocream ab80017903 feat: add iterator flashcards, sync script, and project scaffolding
- iterator.org: C++ iterator flashcard deck
- questions.org: LeetCode question index (217, 242)
- inbox.org: learning inbox with two-sum implementation and notes
- sync-anki.sh: batch sync org files to Anki via emacsclient
- AGENTS.md: conventions for AI agents working in this repo

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 00:48:31 +08:00

1.5 KiB

Inbox

1. two sum

class Solution {
public:
  vector<int> twoSum(vector<int> &nums, int target) {
    vector<pair<int, int>> rev;
    // Fix 1 & 2: Loop over nums.size() and push nums[i]
    for (int i = 0; i < nums.size(); i++) {
      rev.push_back({nums[i], i});
    }

    std::sort(rev.begin(), rev.end());

    for (int i = 0; i < rev.size(); i++) {
      int want = target - rev[i].first;
      // Fix 3: Pass the SORTED vector 'rev' to the search
      int j = bs(rev, want, i + 1);
      if (j >= 0) {
        int a = rev[i].second;
        int b = rev[j].second;
        return vector<int>{min(a, b), max(a, b)};
      }
    }
    return {};
  }

  // Updated to handle vector of pairs
  using PairIter = vector<pair<int, int>>::iterator;

  PairIter lower_bound(PairIter l, PairIter r, int target) {
    while (l < r) {
      PairIter mid = l + (r - l) / 2;
      if (mid->first >= target) { // Access value via .first or ->first
        r = mid;
      } else {
        l = mid + 1;
      }
    }
    return l;
  }

  int bs(vector<pair<int, int>> &indexedNums, int target, int offset) {
    auto it =
        lower_bound(indexedNums.begin() + offset, indexedNums.end(), target);
    if (it == indexedNums.end() || it->first != target) {
      return -1;
    }
    return it - indexedNums.begin();
  }
};

using PairIter = vector<pair<int, int>>::iterator; what is using?

we need to write binary search, lower bound search

learn about binary search functions the natural one by god