• LeetCode-为什么某些测试用例下,执行代码返回结果正确,但提交解答却出错了


    力扣 • 发表于:2018年10月26日 早上 00:33:03 • 更新于:2019年10月08日 下午 2:46:18

    这一类问题的出现,主要有几个原因:

    a. 您的程序使用了全局变量或者自定义的类内变量。

    力扣的判题机在读取您的代码后,对每个测试用例,都会初始化一次类,但全局变量和类内静态变量需要您手动初始化。例如,在第一题(两数之和)的判题过程中:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    int globalVariable = 0;
    class Solution {
    public:
        int classVariable = 0;
        vector<int> twoSum(vector<int>& nums, int target) {
            classVariable++;
            globalVariable++;       
            return {classVariable, globalVariable};
        };
    };

    这样的代码在运行两次test case后,输出的结果会是[1, 1], [1, 2]。

    为了避免这样的问题,一般有两种解决方法:

    1、避免申明类内静态变量以及全局变量。

    2、在 twoSum 内对全局变量初始化。

    b. 您的代码存在细微的问题,如变量没有初始化。

    在使用中遇到题目问题,也可至 力扣圈子 进行题目交流,发布时描述清楚您的问题及使用场景,以获得更好的支持哟~

    转自LeetCode。传送门:https://support.leetcode-cn.com/hc/kb/article/1194344/

  • 相关阅读:
    简单的语句统计所有用户表尺寸大小
    CodeSmith 介绍
    Oracle Partition By 的使用
    Oracle Contact By的使用
    正则提取 html 里<input> 标记的value 值
    IOS 7 风格Checkbox
    aspose words 介绍
    大规模web 服务开发技术
    数学之美 读后感
    工作流简介--(转)
  • 原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/13284971.html
Copyright © 2020-2023  润新知