Algorithm - Binary Search Problem

이소라·2022년 10월 24일
0

Algorithm

목록 보기
28/77

LeetCode Problem : Vaild Perfect Square

  • Given a positive integer num, write a function which returns true if num is a perfect square else false.
  • Follow up: Do not use any built-in library function such as sqrt.
    • Constraints:
      • 1 <= num <= 2^31 - 1
  • Example 1:
    • Input: num = 16
    • Output: true
  • Example 2:
    • Input: num = 14
    • Output: false

Solution

/**
 * @param {number} num
 * @return {boolean}
 */

// 이중 for 문을 이용한 풀이
var isPerfectSquare = function(num) {
    let base = 0;
    while (num >= base**2) {
        if (num === base**2) {
            return true;
        }
        base++;
    }
    return false;
};

// binary search를 이용한 풀이
var isPerfectSquare = function(num) {
    let low = 1;
    let high = num;
    let mid, square;
    while (low <= high) {
        mid = Math.floor((low + high)/2);
        square = mid * mid;
        if (num === square) {
            return true;
        }
        if (num < square) {
            high = mid - 1;
        }
        if (num > square){
            low = mid + 1;
        }
    }
    return false;
};

LeetCode Problem : The K Weakest Rows in a Matrix

  • You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row.

  • A row i is weaker than a row j if one of the following is true:

    • The number of soldiers in row i is less than the number of soldiers in row j.
    • Both rows have the same number of soldiers and i < j.
  • Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.

  • Example 1:

    • Input: mat = [[1,1,0,0,0],[1,1,1,1,0],[1,0,0,0,0], [1,1,0,0,0],[1,1,1,1,1]], k = 3
    • Output: [2, 0, 3]
    • Explanation:
      • The number of soldiers in each row is:
      • Row 0: 2
      • Row 1: 4
      • Row 2: 1
      • Row 3: 2
      • Row 4: 5
      • The rows ordered from weakest to strongest are [2,0,3,1,4].

Solution

/**
 * @param {number[][]} mat
 * @param {number} k
 * @return {number[]}
 */

// map, filer, sort를 사용한 풀이
var kWeakestRows = function(mat, k) {
    const result = [];
    let soldierArray = mat.map((array, index) => {
       const soldierCount = array.filter((num) => num === 1).length;
        return [soldierCount, index];
    });
    soldierArray.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
    for (let i = 0; i < k; i++) {
        result.push(soldierArray[i][1]);
    }
    return result;
};

LeetCode Problem : Longest Increasing Subsequence

  • Given an integer array nums, return the length of the longest strictly increasing subsequence.

  • A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].

    • Constraints:
      • 1 <= nums.length <= 2500
      • 10^4 <= nums[i] <= 10^4
  • Example 1:

    • Input: nums = [10,9,2,5,3,7,101,18]
    • Output: 4
    • Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
  • Example 2:

    • Input: nums = [0,1,0,3,2,3]
    • Output: 4
  • Example 3:

    • Input: nums = [7,7,7,7,7,7,7]
    • Output: 1

Solution

/**
 * @param {number[]} nums
 * @return {number}
 */

// forEach, findIndex를 사용한 풀이
var lengthOfLIS = function(nums) {
    const subsequence = [nums[0]];
    let numberIndex;
    
    nums.forEach((number) => {
        if (number > subsequence[subsequence.length - 1]) {
            subsequence.push(number);
        } else {
            numberIndex = subsequence.findIndex((value) => value >= number);
            subsequence[numberIndex] = number;
        }
    });
    
    return subsequence.length;
};
// binary search를 사용한 풀이
var lengthOfLIS = function(nums) {
    const subsequence = [];
    let currNumber, index;
    
    subsequence[0] = nums[0];
    
    if(!nums.length) return 0;
    
    for (let i = 1; i < nums.length; i++) {
        currNumber = nums[i];
        if (currNumber < subsequence[0]) {
            subsequence[0] = nums[i];
        } else if (currNumber > subsequence[subsequence.length - 1]) {
            subsequence.push(nums[i]);
        } else {
            index = binarySearch(subsequence, currNumber);
            subsequence[index] = currNumber;
        }
    }
    
    function binarySearch(array, value) {
        let start = 0;
        let end = array.length - 1;
        let middle;
        
        while (start < end) {
            middle = Math.floor((start + end)/2);
            
            if (array[middle] >= value) {
                end = middle;
                
            } else {
                start = middle + 1;
            }
        }
       
        return end;
    }
    
    return subsequence.length;
};

Programmers Problem : 입국심사

  • n명이 입국심사를 위해 줄을 서서 기다리고 있습니다. 각 입국심사대에 있는 심사관마다 심사하는데 걸리는 시간은 다릅니다.
  • 처음에 모든 심사대는 비어있습니다. 한 심사대에서는 동시에 한 명만 심사를 할 수 있습니다. 가장 앞에 서 있는 사람은 비어 있는 심사대로 가서 심사를 받을 수 있습니다. 하지만 더 빨리 끝나는 심사대가 있으면 기다렸다가 그곳으로 가서 심사를 받을 수도 있습니다.
  • 모든 사람이 심사를 받는데 걸리는 시간을 최소로 하고 싶습니다.
  • 입국심사를 기다리는 사람 수 n, 각 심사관이 한 명을 심사하는데 걸리는 시간이 담긴 배열 times가 매개변수로 주어질 때, 모든 사람이 심사를 받는데 걸리는 시간의 최솟값을 return 하도록 solution 함수를 작성해주세요.
    • 제한 사항
      • 입국심사를 기다리는 사람은 1명 이상 1,000,000,000명 이하입니다.
      • 각 심사관이 한 명을 심사하는데 걸리는 시간은 1분 이상 1,000,000,000분 이하입니다.
      • 심사관은 1명 이상 100,000명 이하입니다.

Solution

function solution(n, times) {
    times.sort((a,b) => a - b);
    let minTime = 0;
    let maxTime = n * times.at(-1);
    let midTime;
    
    while (minTime <= maxTime) {
        midTime = Math.floor((minTime + maxTime) / 2);
        const count = times.reduce((count, time) => count + Math.floor(midTime/time), 0);
        
        if (count >= n) {
            maxTime = midTime - 1;
        } else {
            minTime = midTime + 1;
        }
    }
    
    return minTime;
}
  • 문제 풀이
    • 구하고자 하는 값 : 최소시간
      • 최소 시간을 구하는 문제이므로 left > right일 때까지 반복해서 진행해야 함 : lower boundary 알고리즘
    • 최대 시간 : 가장 오래 걸리는 심사대에 모든 사람이 들어갈 경우 걸리는 시간
    • 이진 탐색 알고리즘 사용
      • mid 시간 동안 심사관들은 몇 명을 처리할 수 있는지 계산
        • 심사관들이 처리하는 명 수가 대기자 수보다 같거나 클 경우, 최대 시간을 줄임
        • 심사관들이 처리하는 명 수가 대기자 수보다 작을 경우, 최소 시간을 늘림

LeetCode Problem : Missing Number

  • Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

    • Constraints
      • n == nums.length
      • 1 <= n <= 10^4
      • 0 <= nums[i] <= n
      • All the numbers of nums are unique.
  • Example 1:

    • Input: nums = [3,0,1]
    • Output: 2
    • Explanation:
      • n = 3 since there are 3 numbers, so all numbers are in the range [0,3].
      • 2 is the missing number in the range since it does not appear in nums.
  • Example 2:

    • Input: nums = [0, 1]
    • Output: 2
    • Explanation:
      • n = 2 since there are 2 numbers, so all numbers are in the range [0,2].
      • 2 is the missing number in the range since it does not appear in nums.

Solution

/**
 * @param {number[]} nums
 * @return {number}
 */
var missingNumber = function(nums) {
    nums.sort((a,b) => a - b);
    let left = 0;
    let right = nums.length;
    let middle;

    while(left < right) {
        middle = Math.floor((left + right)/2);
        console.log(middle, nums[middle]);

        if (nums[middle] > middle) {
            right = middle;
        } else {
            left = middle + 1;
        }
    }

    return left;
};
  • 풀이
    • '빠진 숫자가 없으면 인덱스와 배열 값이 같다'는 것을 이용함
      • 중간값이 중간 인덱스와 같으면, 중간 인덱스까지는 빠진 숫자가 없으므로 중간 인덱스 이후의 배열을 탐색함
      • 중간값이 중간 인덱스보다 크다면, 중간 인덱스까지에서 빠진 숫자가 있으므로 중간 인덱스 이까지의 배열을 탐색함



LeetCode Problem : Peak Index in a Mountain Array

  • An array arr a mountain if the following properties hold:

    • arr.length >= 3
    • There exists some i with 0 < i < arr.length - 1 such that:
      • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
      • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
  • Given a mountain array arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1].

  • You must solve it in O(log(arr.length)) time complexity.


Solution

/**
 * @param {number[]} arr
 * @return {number}
 */
var peakIndexInMountainArray = function(arr) {
    let start = 0;
    let end = arr.length - 2;
    let middle;

    while (start <= end) {
        middle = Math.floor((start + end)/2);
        if (arr[middle] < arr[middle + 1]) {
            start = middle + 1;
        } else {
            end = middle - 1;
        }
    }
    return start;
};



LeetCode Problem : Capacity To Ship Packages Within D Days

  • A conveyor belt has packages that must be shipped from one port to another within days days.

  • The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.

  • Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.

Constraints

  • 1 <= days <= weights.length <= 5 * 104
  • 1 <= weights[i] <= 500

Examples

  • Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5
  • Output: 15
  • Explanation : A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
    • 1st day: 1, 2, 3, 4, 5
    • 2nd day: 6, 7
    • 3rd day: 8
    • 4th day: 9
    • 5th day: 10
    • Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.

Solution

/**
 * @param {number[]} weights
 * @param {number} days
 * @return {number}
 */
var shipWithinDays = function(weights, days) {
    let minCapacity = Math.max(...weights);
    let maxCapacity = weights.reduce((a,b) => a + b, 0);
    let midCapacity;

    const calculateShipDays = (capacity) => {
        let shipDays = 1;
        let currentCapacity = capacity;
        for (const weight of weights) {
            if (weight > currentCapacity) {
                currentCapacity = capacity;
                shipDays++;
            }
            currentCapacity -= weight;
        }
        return shipDays;
    };
    
    while (minCapacity <= maxCapacity) {
        midCapacity = Math.floor((minCapacity + maxCapacity)/2);
        if (calculateShipDays(midCapacity) > days) {
            minCapacity = midCapacity + 1;
        } else {
            maxCapacity = midCapacity - 1;
        }
    }

    return minCapacity;
};

0개의 댓글