c++ - 检查 N 及其双精度是否存在
问题描述
这是来自 leetcode 教程中的一个问题,它要求:
给定一个整数数组 arr,检查是否存在两个整数 N 和 M,使得 N 是 M 的双倍(即 N = 2 * M)。
这是我尝试的解决方案:
class Solution {
public:
bool checkIfExist(vector<int>& arr) {
for(int i = 0; i < arr.size(); i++){
for(int j = 0; j < i; j++){
if (arr[i] == 2*arr[j]){
return true;}
}
}
}
};
我最终得到了错误:
Line 10: Char 1: error: non-void function does not return a value in all control paths [-Werror,-Wreturn-type]
}
^
1 error generated.
我在这里做错了什么?
编辑:我通过按照建议添加 return false 语句来修复错误,并且还修复了 j 上的循环以运行直到 arr.size()。但是 leetcode 仍然不会接受我的解决方案。它通过了编译测试,但没有通过提交:
现在这是怎么回事?它不识别数组中的负值吗?抱歉,如果这些是非常愚蠢的问题,我对一般编程还是很陌生,感觉我应该提到这一点。
解决方案
我们也可以使用 astd::unordered_map
来解决这个问题:
// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <vector>
#include <unordered_map>
static const struct Solution {
using ValueType = std::uint_fast16_t;
static bool checkIfExist(
const std::vector<int>& arr
) {
std::unordered_map<ValueType, ValueType> num_counts;
for (const auto& num : arr) {
++num_counts[num];
}
for (const auto& num : arr) {
if (
(num && num_counts.find(num * 2) != std::end(num_counts)) ||
(!num && num_counts[num] > 1)
) {
return true;
}
}
return false;
}
};
代码
struct Solution {
static bool checkIfExist(
const std::vector<int>& arr
) {
std::unordered_map<int, int> num_counts;
for (const auto& num : arr) {
++num_counts[num];
}
for (const auto& num : arr) {
if (
(num && num_counts.find(num * 2) != std::end(num_counts)) ||
(!num && num_counts[num] > 1)
) {
return true;
}
}
return false;
}
};
推荐阅读
- android - 这甚至可以使用BLE和智能手机APP吗
- javascript - 如何在reactjs中将类切换到div元素?
- ember.js - 架构问题 - 使用子路由与组件
- python - 在尝试运行单元测试时尝试相对导入超出顶级包
- jquery - 如何使用 Jquery 隐藏 DOM 元素 - 不重复
- ssl - https 不适用于我安装的 ssl (apache 2.4.25 &letsencrypt)
- javascript - 通过属性 js 获取选择器
- php - Ajax 删除表中的数据时不刷新 - Laravel
- javascript - 单击后切换下拉列表,而不是单击开始时
- python - Pandas 在大于 0.21.0 的版本上使用带有 sum() 的 fillna() 返回不同的结果