Leetcode头文件

平时做题的时候,经常会出一些错误需要在本地 debug。新建文件写 Solution ,然后添加测试用例 balabala,很多工作都是重复的,比如添加头文件,读取测试数据,打印列表之类的工作。这些东西都可以提前写好放到一个 common.h 里的。在这里简单记录一下我的做法,所有的代码在这里

头文件

无非就是常用的一些容器和算法库

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <deque>
#include <fstream>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
using namespace std;

打印

我们经常要打印一个列表来检查输出,我用了一个模板函数,这样便于扩展,方便使用。现在只用到了 vector<int>,我就只写了这一种类型的实现,其他可遍历的容器类型同理

template <typename T>
void print(const T& v) {
  cout << "(print not implemented)" << endl;
}

template <>
void print(const vector<int>& v) {
  if (v.empty()) {
    cout << "(empty)" << endl;
    return;
  }
  cout << "[" << v[0];
  for (int i = 1; i < v.size(); ++i) {
    cout << ", " << v[i];
  }
  cout << "]" << endl;
}

template <>
void print(const int& v) {
  cout << v << endl;
}

读取数据

在 leetcode 中,最常见的输入数据就是类似于 [1,2,...] 这样的数组了,我也写了一个函数通过字符串读取来处理

template <typename T>
T load(const string& values) {
  cout << "(load not implemented)" << endl;
}

template <>
vector<int> load(const string& values) {
  vector<int> result;
  int         cursor = 0;
  while (true) {
    while (cursor < values.size() && !isdigit(values[cursor])) ++cursor;
    if (cursor == values.size()) break;
    int num = 0;
    while (cursor < values.size() && isdigit(values[cursor])) {
      num *= 10;
      num += values[cursor++] - '0';
    }
    result.push_back(num);
  }
  return result;
}

例子

我们以870 - 优势洗牌为例,个人感觉用起来还是挺舒服的

#include "common.h"

class Solution {
 public:
  vector<int> advantageCount(vector<int>& nums1, vector<int>& nums2) {
    int         n = nums1.size(), ids[n];
    vector<int> ans(n);
    sort(nums1.begin(), nums1.end());
    iota(ids, ids + n, 0);
    sort(ids, ids + n, [&](int i, int j) { return nums2[i] < nums2[j]; });
    int left = 0, right = n - 1;
    for (const auto& x : nums1) {
      ans[x > nums2[ids[left]] ? ids[left++] : ids[right--]] = x;
    }
    return ans;
  }
};

int main(int argc, char const* argv[]) {
  auto     vec1 = load<vector<int>>("[12,24,8,32]");
  auto     vec2 = load<vector<int>>("[13,25,32,11]");
  Solution solution;
  auto     result = solution.advantageCount(vec1, vec2);
  print(result);
  return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值