写在前面

想在现有的技术栈上,提高 C++ 的技能点。

这是新时代的学习方法:AI托举,边做边学。

目录

做题

知识点

1. 类 class 权限定义

2. 成员访问运算符

3. inline关键字


做题

这道题出现在腾讯WXG后台一面的考察中(牛客网@MRWu_haha分享),所以想试试。

做题思路

有点意思啊。一开始觉得坑(左右边界)不好定义,就想着逐层扫,没想到超时了....信心严重受挫!然后回去继续定义坑,然后运行时间超过 5% 🤦!

然后去看了下题解,有说 动态规划、有说 “双指针” 的。我不太能从题目直接联想得到这些解法~按自己的理解重新思考下:

左右两杆喷枪,计算没有被喷到的块数。

题解

class Solution {
public:
    int trap(vector<int>& height) {
        int capacity = 0;
        int height_size = height.size();
        int left_wall_max_height = height[0];
        int right_wall_max_height = height[height_size - 1];
        int left = 0, right = height_size - 1;
        while (left < right)
        {
            left_wall_max_height = max(left_wall_max_height, height[left]);
            right_wall_max_height = max(right_wall_max_height, height[right]);
            // 左右两杆喷枪,计算没有被喷到的块数。
            if (left_wall_max_height < right_wall_max_height){ 
                // 矮侧才会被喷到,此时 left 是矮侧。
                capacity += left_wall_max_height - height[left]; // 左侧是能喷的,没喷到的是。
                left++;
            }else{
                capacity += right_wall_max_height - height[right];
                right--;
            }
        }
        return capacity;

    }
};

知识点

1. 类 class 权限定义

类成员可以被定义为 public、private 或 protected。默认情况下是定义为 private。

class Name{
    public:
    private:
    protected:
};
2. 成员访问运算符

.: 对象实例 访问 成员用。

->: 指针 访问 成员用。

::: 作用域 访问 成员用。

class Person {
public:
    string name;
    static int population;
};

// 对象实例 - 使用 .
Person alice;
alice.name = "Alice";

// 指针 - 使用 ->
Person* bob = new Person();
bob->name = "Bob";

// 静态成员 - 使用 ::
Person::population = 2;
3. inline关键字

在头文件中使用 inline(最常见)

  • 头文件中:inline 是必须的(避免 ODR 违规)
  • .cpp 文件中:inline 是可选的(只是给编译器的建议)
  • 类内直接实现:自动成为 inline
  • 现代实践:在 .cpp 中优先使用匿名命名空间,在头文件中仍然需要 inline
class Calculator {
public:
    int add(int a, int b);  // 声明
};

// 类外实现成员函数 - 必须在头文件中用 inline
inline int Calculator::add(int a, int b) {
    return a + b;
}
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐