作者stayhungry (跳跳跳跳虎)
看板C_and_CPP
标题[问题] LeetCode 136.Single Number
时间Sat Mar 16 15:02:12 2019
开发平台(Platform): (Ex: Win10, Linux, ...)
Win8.1
编译器(Ex: GCC, clang, VC++...)+目标环境(跟开发平台不同的话需列出)
GCC
额外使用到的函数库(Library Used): (Ex: OpenGL, ...)
问题(Question):
各位前辈大家好
主要问题是在Code Blocks执行时能回传正确的结果,但在leetcode 会显示error,想请教error 的原因及如何修改程式码
题目要求是输入一个整数阵列,回传只在阵列中出现一次的数字,答案唯一。
我的想法是先用qsort()将阵列中的数字排序,排序完
如果第一个数字 不等於 第二个数字
=>回传第一个数字
如果最後一个数字 不等於 倒数第二个数字
=>回传最後一个数字
如果第 i 个数字不等於第 i - 1个数字且不等於第 i + 1个数字( i 为第二个数字~倒数第二个数字)
=>回传第 i 个数字
喂入的资料(Input):
{2, 3, 4, 2, 5, 4, 3}
预期的正确结果(Expected Output):
在Code Blocks 执行完回传5,为正确预期结果
错误结果(Wrong Output):
在leetcode submit 之後,显示 runtime error :heap-buffer-overflow
程式码(Code):(请善用置底文网页, 记得排版,禁止使用图档)
https://pastebin.com/rDDm8Nr9
补充说明(Supplement):
-----
Sent from JPTT on my Asus ASUS_Z01KDA.
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 122.121.55.226
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1552719735.A.DFB.html
※ 编辑: stayhungry (122.121.55.226), 03/16/2019 15:06:43
※ 编辑: stayhungry (122.121.55.226), 03/16/2019 15:08:59
1F:推 idiont: Note: 03/16 15:26
2F:→ idiont: Your algorithm should have a linear runtime complexity 03/16 15:26
3F:→ idiont: . Could you implement it without using extra memory? 03/16 15:26
4F:→ aa0917954358: array的长度如果是0或1就会爆了吧? 03/16 15:27
5F:→ stayhungry: 感谢大大,只注意到题目写阵列为non-empty,忘了考虑 03/16 15:45
6F:→ stayhungry: 到只有一个元素的情况,在leetcode 加上条件 03/16 15:45
7F:→ stayhungry: if(numsSize == 1) return nums[0]可以顺利执行 03/16 15:45
8F:→ stayhungry: qsort 的runtime也有可能是error的原因吗? 03/16 15:52
9F:→ stayhungry: 查cplusplus.com的qsort complexity :Unspecified,but 03/16 15:52
10F:→ stayhungry: quicksorts are generally linearithmic in num,on a 03/16 15:52
11F:→ stayhungry: verage,calling compar approximately num*log2(num) 03/16 15:52