[JavaScript] leetCode : Single Number
728x90

๋ฌธ์ œ

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.

์ •์ˆ˜์˜ ๋ฐฐ์—ด์—์„œ ๋™์ผํ•˜๊ฒŒ ์ง์ง€์–ด์ง€์ง€ ์•Š๋Š” ํ•˜๋‚˜์˜ ์ˆ˜๋ฅผ ์ฐพ์•„ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฌธ์ œ.

 

 

ํ’€์ด

  let result = nums[0];

  for (let i = 1; i < nums.length; i++) {
    result = result ^ nums[i];
  }

  return result;

๊ฐ„๋‹จํ•ด๋ณด์ด๋ฉด์„œ๋„ ๋ฌ˜ํ•˜๊ฒŒ ๊ฐ„๋‹จํ•˜์ง€ ์•Š์•„์„œ ๊ฒฐ๊ตญ ๋‹ค๋ฅธ ์ฝ”๋“œ๋ฅผ ๋ณด๊ฒŒ ๋˜์—ˆ๋‹ค ๐Ÿ˜‡
๋…ผ๋ฆฌ ์—ฐ์‚ฐ์—์„œ XOR์˜ ๊ฐœ๋…์„ ์•Œ๊ณ  ์žˆ๋‹ค๋ฉด ๋ฌด์ง„์žฅ ๊ฐ„๋‹จํ•˜๊ฒŒ ํ’€๋ฆฌ๋Š” ๋ฌธ์ œ์˜€๋‹ค.

 

์ง€๊ธˆ๊นŒ์ง€ ๋น„ํŠธ์—ฐ์‚ฐ์ž๋Š” ๋ณ„๋กœ ์จ๋ณธ ์ ์ด ์—†์—ˆ๊ธฐ์—..
๋น„ํŠธ์—ฐ์‚ฐ์ž ์ค‘ XOR ์—ฐ์‚ฐ์ž(^)์— ๋Œ€ํ•ด ๊ฐ„๋žตํ•˜๊ฒŒ ๊ธฐ๋กํ•ด๋ณธ๋‹ค.

์šฐ์„  ๋ฐฐํƒ€์  ๋…ผ๋ฆฌํ•ฉ์ธ XOR์˜ ์ง„๋ฆฌํ‘œ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.
๊ฐ™์ง€ ์•Š์„ ๋•Œ ์ฐธ(1)์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

 

์ด์ œ ๋‘ ์ˆ˜๋ฅผ ๋น„ํŠธ๋กœ ๋”ฐ์ ธ์„œ ๋’ค์—์„œ๋ถ€ํ„ฐ ๊ฐ™์ง€ ์•Š์œผ๋ฉด 1, ๊ฐ™์œผ๋ฉด 0 ์œผ๋กœ ์ฒ˜๋ฆฌ๋˜๋Š” ์‹์œผ๋กœ ๊ณ„์‚ฐ์ด ๋˜๋Š”.. ๊ทธ๋Ÿฐ ์‹.

 

์•„๋ž˜์™€ ๊ฐ™์€ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๊ฐ€ ์žˆ์„ ๋•Œ

[4,1,2,1,2]

 

๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ฒฐ๊ณผ๊ฐ€ ๋‚˜์˜ค๋Š” ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค. 

์œ„ ๊ฒฐ๊ณผ๋ฅผ ํ’€์–ด์„œ ์จ๋ณด๋ฉด,

1. 4์™€ 1์€ ๊ฐ™์ง€ ์•Š์œผ๋‹ˆ(์ฐธ) ๋”ํ•œ๋‹ค.

2. (4+1)๊ณผ 2๋Š” ๊ฐ™์ง€ ์•Š์œผ๋‹ˆ(์ฐธ) ๋”ํ•œ๋‹ค.

3. (4+1+2)์™€ 1์€ ๋จผ์ € ๋”ํ•ด์ง„ 1๊ณผ ๊ฒน์น˜๋‹ˆ(๊ฑฐ์ง“) ๋บ€๋‹ค.

4. (4+2)์™€ 2๋Š” ๋จผ์ € ๋”ํ•ด์ง„ 2๊ฐ€ ๊ฒน์ณ๋‹ˆ(๊ฑฐ์ง“) ๋บ€๋‹ค.

5. 4๋งŒ ๋‚จ๋Š”๋‹ค.

 

์ด๋Ÿฐ ์‹์œผ๋กœ ์ฝ”๋“œ๊ฐ€ ์ง„ํ–‰๋œ๋‹ค. 

 

์œ„ํ‚ค๋ฐฑ๊ณผ๋ฅผ ๋ณด๋‹ค๋ณด๋‹ˆ ์ด๋Ÿฐ ์‹์œผ๋กœ ์ง์ˆ˜ ํ™€์ˆ˜ ํŒจ๋ฆฌํ‹ฐ๋ฅผ ๊ณ„์‚ฐํ•ด์„œ ์˜ค๋ฅ˜ ๊ฒ€์ถœ์— ์‚ฌ์šฉํ•œ๋‹ค๊ณ  ํ•˜๊ณ ,

์ด๋Ÿฐ ๋ฐฉ์‹์œผ๋กœ ๋งŒ๋“ค์–ด์ง„ ํŒจํŠธ๋ฆฌ ํŠธ๋ฆฌ๋„ ์žˆ๋‹ค๊ณ  ํ•œ๋‹ค. ํฅ๋ฏธ๋กœ์šด ์‚ฌ์‹ค ๐Ÿค”

 

 

728x90

'๐Ÿ““ Algorithm > LeetCode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[JavaScript] leetCode : Reverse Words in a String  (0) 2022.05.16
[JavaScript] leetCode : Implement strStr()  (0) 2022.05.12
[JavaScript] leetCode : Longest Common Prefix  (0) 2022.05.09
[JavaScript] leetCode : Linked List Cycle II  (3) 2022.05.03
[JavaScript] leetCode : Valid Mountain Array  (3) 2022.05.02