[問題] LeetCode 136.Single Number

看板C_and_CPP (C/C++)作者 (跳跳跳跳虎)時間7年前 (2019/03/16 15:02), 7年前編輯推噓2(2010)
留言12則, 4人參與, 7年前最新討論串1/1
開發平台(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://www.ptt.cc/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

03/16 15:26, 7年前 , 1F
Note:
03/16 15:26, 1F

03/16 15:26, 7年前 , 2F
Your algorithm should have a linear runtime complexity
03/16 15:26, 2F

03/16 15:26, 7年前 , 3F
. Could you implement it without using extra memory?
03/16 15:26, 3F

03/16 15:27, 7年前 , 4F
array的長度如果是0或1就會爆了吧?
03/16 15:27, 4F

03/16 15:45, 7年前 , 5F
感謝大大,只注意到題目寫陣列為non-empty,忘了考慮
03/16 15:45, 5F

03/16 15:45, 7年前 , 6F
到只有一個元素的情況,在leetcode 加上條件
03/16 15:45, 6F

03/16 15:45, 7年前 , 7F
if(numsSize == 1) return nums[0]可以順利執行
03/16 15:45, 7F

03/16 15:52, 7年前 , 8F
qsort 的runtime也有可能是error的原因嗎?
03/16 15:52, 8F

03/16 15:52, 7年前 , 9F
查cplusplus.com的qsort complexity :Unspecified,but
03/16 15:52, 9F

03/16 15:52, 7年前 , 10F
quicksorts are generally linearithmic in num,on a
03/16 15:52, 10F

03/16 15:52, 7年前 , 11F
verage,calling compar approximately num*log2(num)
03/16 15:52, 11F

03/16 17:32, 7年前 , 12F
文章代碼(AID): #1SZ9zttx (C_and_CPP)
文章代碼(AID): #1SZ9zttx (C_and_CPP)