这是我在 Leetcode 上遇到的问题。限制条件是:
n == nums.length
1 <= n <= 104
0 <= nums[i] <= n
All the numbers of nums are unique.
我的代码是:
#include<iostream>
#include<vector>
using namespace std;
int a = 0, x = 0;
class Solution {
public:
int missingNumber(vector<int>& nums) {
for(int i = 0; i <= 3; i++) {
for(int j = 0; j < 3; j++) {
if(i == nums[j]) {
a = 1;
break;
}
else {
a = 0;
x = i;
}
}
if(a == 0) {
cout << x;
}
}
return x;
}
};
int main() {
vector<int> nums = {3, 0, 1};
Solution().missingNumber(nums);
}
我在普通编译器上尝试过它给出了正确的输出。但在 Leetcode 上尝试时却出现错误:
Error is Line 52:
Char 5: error: conflicting types for 'main'
52 | int main(int argc, char *argv[]) {
| ^
Line 33: Char 9: note: previous definition is here
33 | int main()
| ^
1 error generated.
有人可以更正我的代码吗?或者告诉我我做错了什么?
您应该只提交具有已实现方法的
Solution
类;法官提供了主要方法。
请注意,您的代码是错误的,因为当应使用
nums.size()
时,它的长度为 3 硬编码。此外,一旦找到丢失的数字,请立即跳出循环,以避免在下一次迭代时覆盖 x
。
for (int i = 0; i <= nums.size(); i++) {
for (int j = 0; j < nums.size(); j++) {
// ...
}
if (a == 0) break;
}