Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
找出陣列中,唯一一個沒有重複的值。
考慮到空間複雜度,無須額外的陣列是否能解決?
Input: [2,2,1]
Output: 1
Input: [4,1,2,1,2]
Output: 4
先排序陣列,
唯一值的條件是,不論前後都不會有相同的值。
var singleNumber = function(nums) {
nums.sort(function(a, b) {
return a - b
})
for (let i = 0; i < nums.length; i += 2) {
if (nums[i] !== nums[i+1] && nums[i] !== nums[i-1]) {
return nums[i]
}
}
};