JavaScript - LeetCode Random Algorithm Test(2)

먹보·2023년 2월 22일
0

1. Palindrome Number (No.0009)

문제 설명

Given an integer x, return true if x is a palindrome, and false otherwise.

해석

정수 x가 주어졌을 때, 만약 x가 대칭수라면 true를 아니라면 false를 반환하는 함수를 구현하세요.

예제

코드

function isPalindrome(x: number): boolean {
    if(x < 0 || (x !== 0 && x % 10 == 0))
        return false;

    let reverse = 0;
    
    while (x > reverse) {
        reverse = reverse * 10 + x % 10;
        x = ~~(x/10);
    }
    
    return x === reverse || x === ~~(reverse/10);
};

🗒️코멘트

2. Valid Boomerang (No.1037)

문제 설명

Given an array points where points[i] = [xi, yi] represents a point on the X-Y plane, return true if these points are a boomerang.
A boomerang is a set of three points that are all distinct and not in a straight line.

해석

3개의 점이 2차원의 배열 형태로 주어졌을 대, 만약 3개의 점이 하나의 직선 위에 있다면 false를 아니라면 true를 반환하는 함수를 구현해주세요.

예제

코드

function isBoomerang(points: number[][]): boolean {
    const x1 = points[0][0]
    const x2 = points[1][0]
    const x3 = points[2][0]
    const y1 = points[0][1]
    const y2 = points[1][1]
    const y3 = points[2][1]
    
    return (x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)!==0) 
};

🗒️코멘트

3. Sort Integers by The Number of 1 Bits (No.1356)

문제 설명

You are given an integer array arr. Sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.
Return the array after sorting it.

해석

정수로 이루어진 배열이 주어졌을 때, 각 정수의 이진법 내에 들어있는 1의 갯수를 기준으로 오름 차순으로 정렬하는 함수를 구현하세요. 만약 비교하려는 2개의 정수의 각 이진법 내 1의 갯수가 같을 경우, 본래 값의 크기를 기준으로 정렬 하시면 됩니다.

예제

코드

/**
 * @param {number[]} arr
 * @return {number[]}
 */
var sortByBits = function(arr) {
    const numOfBits = function(num) {
        const bits = num.toString(2).match(/1/g);
        return bits ? bits.length : 0;
    }
    return arr.sort((a, b) => numOfBits(a) - numOfBits(b) || a - b);
};

🗒️코멘트

4. Defanging an IP Address (No.1108)

문제 설명

Given a valid (IPv4) IP address, return a defanged version of that IP address.
A defanged IP address replaces every period "." with "[.]".

해석

IP 주소가 주어졌을 때, 그 IP 주소의 'Defanged Version'을 반환하는 함수를 구현해주세요.

'Defanged Version'이란 IP 주소의 '.'을 '[.]'으로 바꿔 나온 주소입니다.

예제

코드

/**
 * @param {string} address
 * @return {string}
 */
var defangIPaddr = function(address) {
   return address.replaceAll(".","[.]")
};

🗒️코멘트

5. Minimum Absolute Difference in BST (No.530)

문제 설명

Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

해석

이진 탐색 트리의 루트가 주어졌을 때, 트리 내에 있는 2개의 노드 값에 차이들 중 최소 절댓값을 반환하는 함수를 구현해주세요.

예제

코드

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var getMinimumDifference = function (root) {
	let arr = [];
	
	const helper = (node) => {
		if (node) {
			helper(node.left);
			arr.push(node.val);
			helper(node.right);
		}
	}
	helper(root);
	
	let min = Infinity;
	for (let i = 0; i < arr.length - 1; i++) {
		const diff = Math.abs(arr[i] - arr[i + 1]);
		min = Math.min(min, diff);
	}
	
	return min;
};

🗒️코멘트

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

0개의 댓글