๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ๋ฐœ/์ž๋ฃŒ๊ตฌ์กฐ & ์•Œ๊ณ ๋ฆฌ์ฆ˜

LeetCode - Missing Number

by 1mj 2022. 5. 30.

https://leetcode.com/problems/missing-number/

 

Missing Number - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

์กฐ๊ฑด

n == nums.length ์ด๊ณ  nums์˜ ๋ชจ๋“  ์ˆซ์ž๋Š” ์ค‘๋ณต์ด ์—†๋‹ค.

nums ๋ฐฐ์—ด์˜ ๊ฐ’์€ 0 <= nums[i] <= n ๋ฅผ ๋งŒ์กฑํ•œ๋‹ค.

 

๋‚ด ์ฝ”๋“œ

- ์ตœ๋Œ“๊ฐ’์„ n์œผ๋กœ ๋ณด๊ณ  ํ•ด๋‹น ๊ฐ’์—์„œ -1์”ฉ ํ•˜๋ฉด์„œ ๋ฐฐ์—ด์— ์—†๋Š” ์ˆซ์ž๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

 

/**
 * @param {number[]} nums
 * @return {number}
 */
var missingNumber = function(nums) {
    let n = nums.length;
    while (n > -1) {
        if (!nums.includes(n)) {
            return n;
        }
        n--;
    }
};

 

๊ฐœ์„  ์ฝ”๋“œ 1

- 0๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ํ•ฉ๊ณ„๋ฅผ ๊ตฌํ•˜๊ณ  nums ๋ฐฐ์—ด์— ์žˆ๋Š” ๊ฐ’์„ ๋บ์„ ๋•Œ ๊ฐ’์ด nums ๋ฐฐ์—ด์— ํฌํ•จ๋˜์ง€ ์•Š์€ ๊ฐ’์ด๋‹ค.

- 0๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ํ•ฉ๊ณ„๋ฅผ ๊ตฌํ•˜๋Š” ๊ณต์‹์€ n(n+1)/2 ์ด๋‹ค.

 

/**
 * @param {number[]} nums
 * @return {number}
 */
var missingNumber = function(nums) {
    let sum = nums.length * (nums.length + 1) / 2
    for (let num of nums) sum -= num;
    return sum;
};

 

- ๋ฐฐ์—ด์˜ ํ•ฉ๊ณ„๋ฅผ ๊ตฌํ•  ๋•Œ for๋ฌธ ๋Œ€์‹  reduce() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

 

/**
 * @param {number[]} nums
 * @return {number}
 */
var missingNumber = function(nums) {
    let sum = nums.reduce((a,b) => a+b, 0);
    return (nums.length) * (nums.length + 1) / 2 - sum;
};

 

๊ฐœ์„  ์ฝ”๋“œ 2

- ๋น„ํŠธ XOR์€ ๊ฐ’์ด ๋‘ ๋ฒˆ ์ ์šฉ๋˜๋ฉด ์ดˆ๊ธฐ ๊ฐ’์œผ๋กœ ๋Œ์•„์˜จ๋‹ค.

- ์ˆœ์„œ๊ฐ€ ๋‹ค๋ฅด๋”๋ผ๋„ ๊ฐ™์€ ๊ฐ’์ด ๋‘ ๋ฒˆ XOR๋˜๋ฉด ์ดˆ๊ธฐ๊ฐ’๊ณผ ๊ฐ™๋‹ค.

- 0๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ๊ฐ’์„ ์ดˆ๊ธฐ๊ฐ’ 0์— XORํ•˜๊ณ  ๋ฐฐ์—ด์˜ ๋ชจ๋“  ์ˆ˜๋ฅผ XORํ•˜๋ฉด ํ•œ ๋ฒˆ๋งŒ XOR๋œ ๊ฐ’์ด ๋‚จ๋Š”๋‹ค.

 

/**
 * @param {number[]} nums
 * @return {number}
 */
var missingNumber = function(nums) {
    let res = nums.length;
    for (let i = 0; i < nums.length; i++)
		  res = res ^ i ^ nums[i];
    return res;
};
๋น„ํŠธ XOR ์—ฐ์‚ฐ์ž (^)
๋Œ€์‘๋˜๋Š” ๋‘ ๋น„ํŠธ๊ฐ€ ์„œ๋กœ ๋‹ค๋ฅด๋ฉด 1์„ ๋ฐ˜ํ™˜ํ•˜๊ณ , ์„œ๋กœ ๊ฐ™์œผ๋ฉด 0์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

 

๋Œ“๊ธ€