首页 > 解决方案 > 检查 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 仍然不会接受我的解决方案。它通过了编译测试,但没有通过提交: 错误

现在这是怎么回事?它不识别数组中的负值吗?抱歉,如果这些是非常愚蠢的问题,我对一般编程还是很陌生,感觉我应该提到这一点。

标签: c++arrayssearch

解决方案


我们也可以使用 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;
    }
};

推荐阅读