JavaScript - LeetCode Random Algorithm Test(1)

먹보·2023년 2월 20일
0

1. Two Sum (No.0001)

문제 설명

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.

해석

정수로 이루어진 배열과 목표가 정수로 주어졌을 때, 만약 배열 안 2개의 정수를 랜덤으로 선택했을 때 그 합이 목표와 같으면 그 2개의 인덱스를 배열의 형태로 반환하는 함수를 구현하세요.

예제

코드

function twoSum(nums: number[], target: number): number[] {
    for(let i = 0 ; i < nums.length ; i++){
        let newTarget = target - nums[i];
        for(let j = i; j < nums.length ; j++){
            if(nums[j+1] === newTarget) return [i,j+1]
        }
    }
};

//// 2번째 솔루션
 function twoSum(nums: number[], target: number): number[] {
    const map = {}
    for (let index = 0; index < nums.length; index++) {
      const element = nums[index]
      const complement = target - element
      if (map[complement] !== undefined) {
        return [map[complement], index]
      } else {
        map[element] = index
      }
    }
    return []
  }

🗒️코멘트

우선 첫 시도는 당연히 for문이다. 가장 기본적인 해결법이고 사실 이 문제는 나이도 자체가 어렵지 않았기에 금방 풀 수 있었다..다음 문장을 보기 전까지는 말이다..

Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?

그렇다..For문을 2번 돌리는 방법 외를 찾아보라고 한다.

처음 20분동안 도저히 생각이 나질 않았다...그래서 혹시 몰라 프로그래머스 문제들을 돌이켜보다가..객체를 활용해 목표 타켓에서 선택된 수를 뺐을 때의 값이 객체 내부 존재여부에 따라 반환하는 방법이 떠올라 그 방법을 활용해 다시 문제를 풀었더니 확실히 속도면에서 우월한 향상을 보여 기분이 좋았다.

2. Check If Two String Arrays are Equivalent (No.1662)

문제 설명

Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.
A string is represented by an array if the array elements concatenated in order forms the string.

해석

문자열로 이루어진 배열 word1 과 word2가 주어졌을 때, 만약 두 배열 내부의 문자가 서로 같다면 참을 만약 같지 않다면 false를 반환해주는 함수를 구현해주세요.

예제

코드

function arrayStringsAreEqual(word1: string[], word2: string[]): boolean {
    return word1.join('') === word2.join("") ? true : false
};

🗒️코멘트 : NULL

3. Next Greater Element I (No.496)

문제 설명

The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.
You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.
For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.
Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.

어우...쓸데없이 길어..내 식대로 바꿔야지...

해석

정수로 이루어진 2개의 배열 A와 B가 주어졌을 때, A[i]가 B[j]에 있을 경우 만약 A[i] 보다 큰 숫자가 B의 j번째 이후에 존재할 경우 그 숫자를 반환하고 만약 없다면 -1을 반환하는 함수를 구현하세요.

예제

코드

function nextGreaterElement(nums1: number[], nums2: number[]): number[] {
    return nums1.map((el) => {
        for(let i = (nums2.indexOf(el)) ; i < nums2.length ; i++){
          if(nums2[i+1] > el){
            return nums2[i+1]
          } 
        } return -1
    })
};

🗒️코멘트

처음으로 함수에 변수를 선언하지 않고 return 에 직접 쓰는 방식으로 로직을 짜봤다. 효율은 좋을 수 있으나..가독성은 좀 떨어지는 것 같은 느낌이 드는 건 나 때문인가?

좋은 코드를 썼나 물어봤을 때, 답변을 잘 하지 못할 것 같다.

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

0개의 댓글