-
-
Notifications
You must be signed in to change notification settings - Fork 422
/
single-number.js
52 lines (44 loc) · 1.05 KB
/
single-number.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* 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?
*
* Example 1:
*
* Input: [2,2,1] Output: 1
*
* Example 2:
*
* Input: [4,1,2,1,2] Output: 4
*
*/
/**
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function(nums) {
result= []
nums.sort()
nums.forEach(element => {
if (result.indexOf(element) == -1){
result.push(element)
}else{
result.splice(result.indexOf(element),1)
}
});
return result[0]
};
//------- Test cases -----------------
// Input: nums = [2,2,1]
// Output: 1
console.log(`Example 01 = ${singleNumber([2,2,1])} expected Output 1.`)
// Input: nums = [4,1,2,1,2]
// Output: 4
console.log(`Example 02 = ${singleNumber([4,1,2,1,2])} expected Output 4.`)
// Input: nums = [1]
// Output: 1
console.log(`Example 03 = ${singleNumber([1])} expected Output 1.`)