Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.

You must write an algorithm that runs in O(n) time and uses only constant extra space.

Example 1:

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

Example 2:

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

Example 3:

Input: nums = [1]
Output: []

난이도: medium

중복된 숫자를 구하는 문제인데, 이 문제는 풀이가 어렵다기 보다는 어떻게 효율적으로 코드를 짤 것인가 떄문에
난이도가 medium으로 측정된듯 싶다

일반적으로 중복되는 숫자를 찾는 문제는 map을 이용하여 풀이 했던 경험이 있어
원래 풀던대로 그대로 풀었는데, 효율이 그닥 좋지 못하다

var findDuplicates = function(nums) {
  const result = [];
  const map = new Map();

  for (let i = 0; i < nums.length; i ++) {
    const number = nums[i];
    const item = map.get(number);

    if (item) {
      result.push(number)
    }
    map.set(number, i + 1)
  }
  return result
};

절대값을 이용하는 풀이가 많이 보이는데 솔직히 이해가 안된다
왜 절대값을 이용하지?

 

반응형

+ Recent posts