LeetCode Js-136. Single Number
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
給予一個非空白的整數陣列 nums,每一個元素皆出現兩次只有一個沒有。
尋找出現一次的元素。
你必須實現具有線性運行複雜度的解決方案,不能使用額外的空間。
Example 1:
<pre style='background-color:#ggg'>
Input: nums = [2,2,1]
Output: 1
Solution:
Code1: two for loop
var singleNumber = function(nums) {
if (nums.length ===1) return nums[0]
let box = {}
for (let i = 0; i < nums.length; i++) {
if (box[nums[i]]) {
box[nums[i]]++
} else {
box[nums[i]] = 1
}
}
for (let i in box) {
if (box[i] === 1) {
return i
}
}
};
Code2: XOR
var singleNumber = function(nums) {
for (let i = 1; i < nums.length; i++) {
nums[0] ^= nums[i]
}
return nums[0]
};
FlowChart:
Example 1
Input: nums = [2,2,1]
nums.length = 3
box = {}
step.1
box = {'2': 1}
box = {'2': 2}
box = {'1': 1, '2': 1}
step.2
box = {'1': 1} = 1, return i //1