init: init commit
All checks were successful
Build and Deploy Quartz / build-and-deploy (push) Has been skipped

This commit is contained in:
2026-01-01 14:16:34 +08:00
commit 4a5acab07d
216 changed files with 40383 additions and 0 deletions

View File

@@ -0,0 +1,42 @@
---
date: 2025-12-26
tags:
- Leetcode
---
We know that Leetcode puts the solution function into a class. Let's check example below:
```cpp
int gv = 0;
class Solution {
public:
int returnSecondElem(int arr[]) {
gv += 1;
cout << gv; // expected to be 1 in each case
return arr[gv];
}
};
```
Here we initialize a global variable `gv` and use it in the solution function `returnSecondElem()`. In this case, we may expected that for each test case, the `cout << gv` will print `1` and the second element of the array is returned.
However, this is not the case. Since `gv` is global variable, and Leetcode seems to use single `Solution` instance for solving all test cases, when first test case finished, the `gv` already became `1`, so for the second test case, program will print `2` and third element will be returned.
-----
If we want to use global variable, we may also want to initialize it at the beginning of the solution method:
```cpp
int gv = 0;
class Solution {
public:
int returnSecondElem(int arr[]) {
// always initialize here!
gv = 0;
gv += 1;
cout << gv;
return arr[gv];
}
};
```