섹션 5: 문제 해결 패턴

선정·2023년 10월 22일
0
post-custom-banner

빈도수 세기 패턴

naive solution

function same(arr1, arr2) {
  if(arr1.length !== arr2.length) {
    return false;
  }
  for(let i=0; i<arr1.length; i++) {
    let correctIndex = arr2.indexOf(arr1[i]**2);
    if(correctIndex === -1) {
      return false;
    }
    arr2.splice(correctIndex, 1)
  }
  return true;
}

same([1, 2, 3], [4, 1, 9]);

refactored solution

function same(arr1, arr2) {
  if(arr1.length !== arr2.length) {
    return false;
  }
  let frequencyCounter1 = {}
  let frequencyCounter2 = {}
  for(let val of arr1) {
    frequencyCounter1[val] = (frequencyCounter1[val] || 0) + 1
  }
  for(let val of arr2) {
    frequencyCounter2[val] = (frequencyCounter2[val] || 0) + 1
  }
  for(let key in frequencyCounter1) {
    if(!(key**2 in frequencyCounter2)) {
      return false
    }
    if(frequencyCounter2[key**2] !== frequencyCounter1[key]) {
      return false
    }
  }
  return true
}

same([1, 2, 3, 2], [9, 1, 4, 4]);

anagram

function validAnagram(str1, str2) {
  if(str1.length !== str2.length) {
    return false
  }
  const frequencyCounter1 = {}
  const frequencyCounter2 = {}
  for(let val of str1) {
    frequencyCounter1[val] = ++frequencyCounter1[val] || 1
  }
  for(let val of str2) {
    frequencyCounter2[val] = ++frequencyCounter2[val] || 1
  }
  for(let key in frequencyCounter1) {
    if(!(key in frequencyCounter2)) {
      return false
    }
    if(frequencyCounter2[key] !== frequencyCounter1[key]) {
      return false
    }
  }
  return true
}

validAnagram('anagram', 'nagaram')
function validAnagram(first, second) {
  if(first.length !== second.length) {
    return false
  }
  let lookup = {};
  for(let i=0; i<first.length; i++) {
    let letter = first[i];
    lookup[letter] ? lookup[letter] += 1 : lookup[letter] = 1;
  }
  for(let i=0; i<second.length; i++) {
    let letter = second[i];
    if(!lookup[letter]) {
      return false;
      } else {
        lookup[letter] -= 1;
      }
  }
  return true
}

validAnagram('anagram', 'nagaram')


MULTIPLE POINTERS

NAIVE SOLUTION

function sumZero(arr) {
  for(let i=0; i<arr.length; i++) {
    for(let j=i+1; j<arr.length; j++) {
      if(arr[i]+arr[j] === 0) {
        return [arr[i], arr[j]];
      }
    }
  }
}

sumZero([-3,-2,-1,0,1,2,3]) // [-3,3]

REFACTOR

function sumZero(arr) {
  let left = 0;
  let right = arr.length - 1;
  while(left < right) {
    let sum = arr[left] + arr[right];
    if(sum === 0) {
      return [arr[left], arr[right]];
    } else if(sum > 0) {
      right--;
    } else {
      left++;
    }
  }
}

sumZero([-4,-3,-1,0,1,2,5])

고유값 세기 솔루션

function countUnuqieValues(arr) {
    if(arr.length === 0) return 0;
    let i = 0;
    for(let j=1; j<arr.length; j++) {
        if(arr[i] !== arr[j]) {
            i++;
            arr[i] = arr[j];
        }
    }
    return i+1;
}
profile
starter
post-custom-banner

0개의 댓글