N

(Leet Code JS)Find All Numbers Disappeared in an Array 본문

Leet Code 알고리즘

(Leet Code JS)Find All Numbers Disappeared in an Array

naeunchan 2022. 5. 13. 15:41
728x90
반응형

https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/

 

Find All Numbers Disappeared in an Array - 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

nums 배열에서 없는 수를 answer에 담아 리턴하면 된다.

1 부터 nums.length 까지의 수가 nums에 담겨있다.

check라는 배열을 length + 1 크기로 선언하고 false로 초기화한다.

 

nums를 순회하면서

nums[i]를 인덱스로 하는 check 배열을 true로 바꿔준다.

 

이후 check 배열을 1부터 length까지 순회한다.

만약 check[i] = false라면 answer에 push한다.

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var findDisappearedNumbers = function(nums) {
    const length = nums.length;
    const answer = [];
    const check = Array(length + 1).fill(false);
    
    for(let i = 0; i < length; i++){
        if(!check[nums[i]]){
            check[nums[i]] = true;
        }
    }
    
    for(let i = 1; i <= length; i++){
        if(!check[i]){
            answer.push(i);
        }
    }
    
    return answer;
};
728x90
반응형

'Leet Code 알고리즘' 카테고리의 다른 글

(Leet Code JS)Hamming Distance  (0) 2022.05.13
(Leet Code JS)Repeated Substring Pattern  (0) 2022.05.13
(Leet Code JS)Arranging Coins  (0) 2022.05.13
(Leet Code JS)Add Strings  (0) 2022.05.13
(Leet Code JS)Third Maximum Number  (0) 2022.05.13