쓰윽터디/코딩테스트

코딩테스트_01

Kkan 2023. 1. 8. 13:24
728x90
반응형

1 주차

[ 2023.01.02 - 2023.01.08 ]

문제 1. Sqrt(x)

 

난이도: 상 중 

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

You must not use any built-in exponent function or operator.

  • For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.

Example 1:

Input: x = 4
Output: 2
Explanation: The square root of 4 is 2, so we return 2.

Example 2:

Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842...,
and since we round it down to the nearest integer, 2 is returned.

Constraints:

  • 0 <= x <= 231 - 1

Answer:

/**
 * @param {number} x
 * @return {number}
 */
const mySqrt = (x) => {
    
    let answer = 0;

    for(let i = 0; i <= x; i++) {
        if(i * i <= x) {
            answer = i
        }
    }
    
    return answer; 
};

문제 2. Find Target Indices After Sorting Array

난이도: 상 중 

 

You are given a 0-indexed integer array nums and a target element target.

A target index is an index i such that nums[i] == target.

Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order.

 

Example 1:

Input: nums = [1,2,5,2,3], target = 2
Output: [1,2]
Explanation: After sorting, nums is [1,2,2,3,5].
The indices where nums[i] == 2 are 1 and 2.

Example 2:

Input: nums = [1,2,5,2,3], target = 3
Output: [3]
Explanation: After sorting, nums is [1,2,2,3,5].
The index where nums[i] == 3 is 3.

Example 3:

Input: nums = [1,2,5,2,3], target = 5
Output: [4]
Explanation: After sorting, nums is [1,2,2,3,5].
The index where nums[i] == 5 is 4.

Constraints:

  • 1 <= nums.length <= 100
  • 1 <= nums[i], target <= 100

Answer:

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
const targetIndices = (nums, target) => {
    let answer = [];
    let sortNums = nums.sort((a, b) => a - b);

    for(let i = 0; i < sortNums.length; i++) {
        if(sortNums[i] === target) {
            answer.push(i)
        }
    }
    return answer;
};

 

728x90
반응형