JavaScript - LeetCode Random Algorithm Test(9)

먹보·2023년 3월 15일
0

1. Smallest Even Multiple (No.2413)

문제 설명

Given a positive integer n, return the smallest positive integer that is a multiple of both 2 and n

해석

양의 정수 n이 주어졌을 때 2와 n의 배수 중 가장 작은 양의 정수를 반환하는 함수를 구현해주세요.

예제

코드

function smallestEvenMultiple(n: number): number {
  let i = 1
  while(n % 2 !== 0){
    i++
    n *= i
  }
  return n 
};
///
function smallestEvenMultiple(n: number): number {
  return n % 2 === 0 ? n : n*2
}

🗒️코멘트

NULL


2. Longest Harmonious Subsequence (No.0594)

문제 설명

We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1.
Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.
A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.

해석

Harmonious Array란 배열의 최댓값과 최솟값의 차이가 정확히 1이 나는 배열을 뜻한다. 만약 정수로 이루어진 배열이 주어 졌을 때, 이 배열의 부분 배열 중 가장 긴 Harmonious Array의 길이를 찾아 반환하는 함수를 구현해주세요. 이 때 부분 배열의 일부 요소는 필요에 따라 삭제할 수는 있지만 요소들의 순서는 바뀌어서는 안됩니다.

예제

코드

function findLHS(nums: number[]): number {
    let res = 0
    const map : Map<number,number> = new Map();
    
    nums.forEach(n => map.has(n) ? map.set(n, map.get(n) + 1) : map.set(n, 1));
    
    for (let key of map.keys()) {
        if(map.has(key - 1)) {
            res = Math.max(res, map.get(key) + map.get(key - 1));
        }
    }
    
    return res;
};

🗒️코멘트

푸는데 상당히 오래 걸렸던 문제, 정확히는 문제의 접근 방식을 어떤 식으로 해야 할지 몰라서 이중 for 문을 돌리면서 풀으려고 했지만 풀리지 않아 한 참을 고민해본 결과...배열 내에 있는 각 숫자의 갯수를 세고 hashmap을 통해 이를 정리해 준 후 키 값의 차이가 1인 것의 합을 구하는 것과 같다고 느껴져 hashmap을 사용해서 풀었더니 해결이 되었다.


3. Assign Cookies (No.0455)

문제 설명

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.

해석

당신은 i 명의 아이들과 같이 살고 있습니다. 각 각의 아이들이 원하는 쿠키의 최소 사이즈를 g[i]라고 하고 병에 들어있는 각 쿠키 j의 사이즈를 s[j]라고 했을 때, 최대 몇 몇의 아이들이 만족하면서 쿠키를 즐길 수 있는지 함수로 구현해주세요.

예제

코드

function findContentChildren(g: number[], s: number[]): number {
  let count = 0;
  s.sort((a,b) => a - b)
  for (let i = 0 ; i < g.length ; i++){
    for (let j = 0 ; j < s.length ; j++){
      if(s[j] >= g[i]) {
      count++
      s.splice(j,1)
      break;
      }
    }
  }
  return count
};
//

🗒️코멘트

NULL

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

0개의 댓글