forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsoobing.ts
More file actions
45 lines (39 loc) ยท 1.22 KB
/
soobing.ts
File metadata and controls
45 lines (39 loc) ยท 1.22 KB
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
/**
* ๋ฌธ์ ์ค๋ช
* - 0๋ถํฐ n๊น์ง ์ซ์๊ฐ ์ค๋ณต ์์ด ๋จ ํ๋๋ง ๋น ์ ธ์๋ ์ซ์ ์ฐพ๊ธฐ
*
* ์์ด๋์ด
* 1) ์ฒดํฌ ๋ฐฐ์ด ์์ฑ
* - 0๋ถํฐ n๊น์ง ์ซ์๊ฐ ์ค๋ณต ์์ด ๋จ ํ๋๋ง ๋น ์ ธ์๋ ์ซ์ ์ฐพ๊ธฐ
*
* 2) ์ํ์ ์ ๊ทผ
* - n*(n+1)/2: ๋ฐฐ์ด์ ํฉ - ์ฃผ์ด์ง ๋ฐฐ์ด์ ํฉ = ๋น ์ง ์ซ์
*
* 3) XOR ํ์ฉ
* - 0 ^ 1 ^ 2 ^ ... ^ n : ๋ชจ๋ ์ซ์ XOR
* - nums[0] ^ nums[1] ^ ... ^ nums[n-1] : ๋ฐฐ์ด ๋ด ์กด์ฌํ๋ ์ซ์๋ค XOR
* - ์ด ๋์ XORํ๋ฉด, ์ค๋ณต๋๋ ์ซ์๋ ๋ชจ๋ ์์๋์ด ๋น ์ง ์ซ์๋ง ๋จ์.
*/
function missingNumber(nums: number[]): number {
const check = new Array(nums.length).fill(false);
nums.forEach((num) => (check[num] = true));
for (let i = 0; i < nums.length; i++) {
if (!check[i]) return i;
}
return nums.length;
}
// ์ํ์ ์ ๊ทผ
function missingNumber2(nums: number[]): number {
const n = nums.length;
const expectedSum = (n * (n + 1)) / 2;
const actualSum = nums.reduce((acc, cur) => acc + cur, 0);
return expectedSum - actualSum;
}
// XOR ํ์ฉ
function missingNumber3(nums: number[]): number {
let xor = 0;
for (let i = 0; i < nums.length; i++) {
xor ^= i ^ nums[i];
}
return xor ^ nums.length;
}