【问题标题】:Check If N and Its Double Exist检查 N 及其双精度是否存在
【发布时间】:2021-01-30 02:53:30
【问题描述】:

这是来自 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 仍然不会接受我的解决方案。它通过了编译测试,但没有通过提交:

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

【问题讨论】:

  • 函数右括号前需要return false;
  • 感谢您指出这一点!我也意识到我应该让 j 上的循环一直运行到 arr.size(),我很傻。

标签: c++ arrays search


【解决方案1】:

如果有 n 个数字,您将循环 n² 次,例如 n == 1_000, 1_000_000 次。

更好的是你保留一组加倍的数字(头脑 2*k 也可以写成 k>1)。 这可以是同一组,complementary_numbers

然后,如果您遇到“任一”集中的数字,您已经找到了解决方案。这只需要 n 步,并且添加到一个集合中最多为 log n,因此复杂度为 O(n.log n) 而不是 O(n²):大约快 100 倍。

【讨论】:

  • 感谢您的评论,我知道这个复杂性问题。我对一般的编程有点陌生,所以只是尝试用我想到的最简单的算法来解决它。
【解决方案2】:

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

【讨论】:

  • 是的,我看到了一些实现此方法的解决方案。这不是我自己研究的东西,希望有一天我能做到。感谢您的评论。
猜你喜欢
  • 2020-06-02
  • 2015-04-11
  • 1970-01-01
  • 1970-01-01
  • 2010-09-20
  • 2019-07-09
  • 2011-11-09
  • 2010-10-08
相关资源
最近更新 更多