Last active
January 25, 2018 11:38
-
-
Save wowdyaln/2de05d5db001095e0beb3dacbd50b733 to your computer and use it in GitHub Desktop.
leetcode_136
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 給一個 array, 一個 ele , | |
function onlyOne(arr, ele) { | |
var count = 0; | |
// 先一個 for loop,算出 arr 裏面有幾個 ele | |
for (var i = 0; i < arr.length; ++i) { | |
if (arr[i] == ele) | |
count++; | |
} | |
// 如果 ele 小於2個,那就是這個 ele 了 | |
if (count < 2) { | |
// 就是這個 ele 了 | |
return ele | |
// 如果大於等於 2個,那把這個 ele 從 arr 中刪除 | |
} else { | |
arr.splice(arr.indexOf(ele), 1) | |
arr.splice(arr.indexOf(ele), 1) | |
// 然後把處理過後的 arr 丟回給 singleNumber | |
return singleNumber(arr) | |
} | |
} | |
var singleNumber = function (nums) { | |
// 由於確定出現一次的 ele 只會有一個,所以先找到就會先跳出程式碼了 | |
return onlyOne(nums, nums[0]) | |
// 如果一開始 nums 只有一個 ele ,就傳回這個 ele | |
return nums[0] | |
} | |
//結果: Time Limit Exceeded |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
簡單數學: | |
2∗(a+b+c) − (a+a+b+b+c) = c | |
*/ | |
function singleNumber( nums ) { | |
var once = [] | |
nums.forEach(ele => { | |
if ( once.indexOf(ele) === -1) | |
once.push(ele) | |
}) | |
var sum_once = once.reduce(add, 0); | |
var sum_nums = nums.reduce(add, 0); | |
function add(a, b) { | |
return a + b; | |
} | |
var hit = sum_once*2 - sum_nums | |
return hit | |
} | |
//結果: Time Limit Exceeded |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
最快方法,使用 XOR | |
A XOR A = 0 | |
(A ^ B) ^ C == A ^ (B ^ C) | |
關於 XOR | |
https://goo.gl/pdehqK | |
x^y == y^x → xor 運算可以隨意換順序 | |
x^x == 0 / → 相同的數字 xor 會剩下 0 | |
x^0 == x → 任何數字跟 0 xor 還是同一個數字 | |
*/ | |
function singleNumber( nums ) { | |
let a = 0 | |
for (var i = 0; i < nums.length; i++){ | |
a = a ^ nums[i] | |
} | |
return a | |
} | |
// 結果 :PASS | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment