[leetcode, JS] 1773. Count Items Matching a Rule

mxxn·2023년 11월 8일
0

leetcode

목록 보기
116/198

문제

문제 링크 : Count Items Matching a Rule

풀이

/**
 * @param {string[][]} items
 * @param {string} ruleKey
 * @param {string} ruleValue
 * @return {number}
 */
var countMatches = function(items, ruleKey, ruleValue) {
    return items.reduce( (acc, cur) => {
        if(ruleKey === 'type' && ruleValue === cur[0]) acc+=1
        if(ruleKey === 'color' && ruleValue === cur[1]) acc+=1
        if(ruleKey === 'name' && ruleValue === cur[2]) acc+=1
        return acc
    }, 0)
};
  1. 배열 items에서 ruleKey와 ruleValue가 일치하는 개수를 찾는 방식
  • Runtime 62ms, Memory 46.44MB

다른 풀이

/**
 * @param {string[][]} items
 * @param {string} ruleKey
 * @param {string} ruleValue
 * @return {number}
 */
var countMatches = function(items, ruleKey, ruleValue) {
     const keys = {
        type: 0,
        color: 1,
        name: 2
    }
    return items.filter(item => item[keys[ruleKey]] === ruleValue).length

};
  1. key의 index를 미리 정해두고 filter로 찾아 length를 return
  • Runtime 55ms, Memory 46.59MB
profile
내일도 글쓰기

0개의 댓글