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