# 287. Find the Duplicate Number ## 題目敘述  題目意思: ## 初步想法 ### 第一次看到 設一個迴圈去跑每個值,出現第一次放入新array中,出現第二次直接印出該數,break ## 解題 ### 作法1 : 將ARRAY先排序,跑迴圈,當此個和下個一樣時,輸出 ``` var findDuplicate = function(nums) { let num_sort = nums.sort() //先排序 for(let i = 0;i <nums.length;i++){ //當排序後會出現一組一樣大的 if(num_sort[i] === num_sort[i+1]) return num_sort[i] } }; ``` ### 最終結果  ### 作法2 : 利用set 利用[set的原理](https://blog.techbridge.cc/2017/02/11/javascript-data-structure-algorithm-set/),還有[這篇](https://medium.com/%E6%BC%AB%E7%AF%89%E8%98%AD%E6%A0%BC/js%E4%B8%AD%E7%9A%84-set-%E8%88%87-map-815a9157b3bf) ps.[了解與Map差異](https://ithelp.ithome.com.tw/articles/10191607) ``` var findDuplicate = function(nums) { const set = new Set(); for (let num of nums){ if (set.has(num)) { return num } set.add(num); } }; ``` ### 最終結果  ###### tags: `Leetcode`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up