Single Number

Jamie·2022년 3월 3일
0

LeetCode

목록 보기
9/18
post-thumbnail

📚문제

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.

Example 1:

Input: nums = [2,2,1]
Output: 1
Example 2:

Input: nums = [4,1,2,1,2]
Output: 4
Example 3:

Input: nums = [1]
Output: 1

Constraints:

1 <= nums.length <= 3 _ 104
-3 _ 104 <= nums[i] <= 3 \* 104
Each element in the array appears twice except for one element which appears only once.

💡풀이

var singleNumber = function (nums) {
    // 중복된 숫자를 넣어줄 repeat 배열을 만들어준다
    // nums를 반복문을 돌면서 repeat에 요소가 포함되어 있지 않으면 repeat에 push를 해준다
    // 포함되어 있으면 Repeat 배열에 들어져 있는 해당 요소를 지운다.
    // 반복문을 다 돌고 나면 repeat의 0번째 요소를 리턴한다.

    let repeat = [];
    for (let i = 0; i < nums.length; i++) {
        if (!repeat.includes(nums[i])) {
            repeat.push(nums[i]);
        } else {
            let index = repeat.indexOf(nums[i]);
            repeat.splice(index, 1);
        }
    }
    return repeat[0];
};

✅ 기본적인 메소드로 풀 수 있는 문제였다. 아주 사소한 차이지만 메소드를 이제는 조금 자연스럽게 문제를 보면서 바로 떠올릴 수 있게 된 느낌이 들어서 다행이다.

profile
공부하고 비행하다 개발하며 여행하는 frontend engineer

0개의 댓글