Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?
요약) 요소중 중복되지 않는 숫자를
return
하라.
var singleNumber = function(nums) { const set = [...new Set(nums)]; const length = set.length for(let i = 0; i < length; i++) { const index = nums.indexOf(set[i]); if(nums.indexOf(set[i], index + 1) < 0) return set[i]; } };
set
로 중복을 먼저 제거하고,set
요소들중numbs
배열에서 제일 먼저 찾아진index
다음에index
가 없으면 그 수를return
.
var singleNumber = function(nums) { for(let i = 0; i < nums.length; i++) { const index = nums.indexOf(nums[i]); if(nums.indexOf(nums[i], index + 1) < 0) return nums[i]; } };
생각해보니 굳이
set
를 쓸 필요가 없어서 자체적으로 찾게끔refactoring
.
var singleNumber = function(nums) { for(let i = 0; i < nums.length; i++) { if(nums.indexOf(nums[i], nums.indexOf(nums[i]) + 1) < 0) return nums[i]; } };
index
를 따로 변수로 만들어도 한 번만 쓰이니까 그냥 없애서 더 짧게.