JavaScript - LeetCode Random Algorithm Test(3)

먹보·2023년 2월 27일
0

1. Roman to Integer (No.0013)

문제 설명

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

해석

로마 숫자를 아라비아 숫자로 바꾸는 함수를 구현하세요.

예제

코드

var romanToInt = function(s) {
    const romanChar = {
        I : 1,
        V : 5,
        X : 10,
        L : 50,
        C : 100,
        D : 500,
        M : 1000
    }
    let sum = 0;
    for (let i = 0 ; i<s.length ; i++){
        if(romanChar[s[i]] >= romanChar[s[i+1]]){
            sum += romanChar[s[i]]
        } else if(!romanChar[s[i+1]]){
            sum += romanChar[s[i]]
        } else {
          sum -= romanChar[s[i]]
        }
    }
    return sum
};

🗒️코멘트

우선 푸는 방식은 다른 사람들과 크게 다르지는 않아 기뻤으나..조건문 처리를 깔끔하게 해주지 못해 아쉬웠다.

        if (cur < next) {
            result += next - cur;
            i++;
        } else {
            result += cur;
        }

다른 예제를 보면 기준이 되는 숫자가 다음 숫자보다 작을 경우 그 차만큼만 더하는 방식을 택해 깔끔하게 예외 처리를 하였으나 나는 그 반대를 택해 마지막 숫자의 다음 숫자가 undefined가 될 경우도 처리를 해주었기 때문에 코득 한 줄 더 길어졌다.

하나의 방식에 꽂히면 다른 방안을 택하지 못하는 경우가 종종 발생하는데 이것은 비단 코딩뿐만 아니라 일상생활에서도 마찬가지다.

하나의 견해에 너무 중독되지 않도록 조심해보자.


2. Longest Common Prefix (No.0014)

문제 설명

Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".

해석

문자열로 이루어진 배열이 주어졌을 때, 공통의 접두어를 찾아 반환하는 함수를 구현하세요.

예제

코드

var longestCommonPrefix = function(strs) {
    const firstWord = strs.shift().split("");
    
    for(let i = 0 ; i < strs.length ; i++){
        firstWord.forEach((el,index) =>{
            if(!strs[i][index]?.includes(el)){
                firstWord.splice(index)
            }
        })
    }
  return firstWord.join("")
};

🗒️코멘트

처음으로 Optional Chanining을 코딩테스트에 적용해보았다.


3. Fair Candy Swap (No.0888)

문제 설명

Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of candies of the jth box of candy that Bob has.
Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have.
Return an integer array answer where answer[0] is the number of candies in the box that Alice must exchange, and answer[1] is the number of candies in the box that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists.

해석

앨리스와 밥은 각 각 i개의 사탕 봉지와 j개의 사탕 봉지를 가지고 있으며 각 봉지 안에는 1개 이상의 사탕이 담겨져 있습니다. 둘은 서로 가지고 있는 사탕 봉지를 교환하여 각자가 가지고 있는 사탕의 갯수의 총합이 같게끔 하려고 하는데요. 이 때 서로 교환하게 될 사탕봉지의 사탕의 갯수를 리턴하는 함수를 구현해주세요.

정담은 2개의 정수로 이루어진 배열이며, 0번째 인덱스에는 앨리스가 교환하게 될 사탕봉지의 사탕 갯수, 1번째 인덱스에는 밥이 교환하게될 사탕봉지의 사탕 갯수라고 생각하면 됩니다.

예제

코드

var fairCandySwap = function(aliceSizes, bobSizes) {
    const aliceSum = aliceSizes.reduce((a,b) => a+b);
    const bobSum = bobSizes.reduce((a,b) => a+b);
    const diff = (aliceSum - bobSum) >> 1;
    const setAlice = new Set(aliceSizes);
    
    for (const candy of bobSizes) {
    if (setAlice.has(candy + diff)) return [candy + diff, candy];
  }
};

🗒️코멘트

비트 연산자에 대해 공부할 수 있어서 좋은 문제였다.

비트연산자

profile
🍖먹은 만큼 성장하는 개발자👩‍💻

0개의 댓글