LeetCode 코딩 문제 2020/12/12 - Single Number

이호현·2020년 12월 12일
0

Algorithm

목록 보기
29/138

[문제]

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를 따로 변수로 만들어도 한 번만 쓰이니까 그냥 없애서 더 짧게.

profile
평생 개발자로 살고싶습니다

0개의 댓글