2485. Find the Pivot Integer (leet code)

임병욱·2023년 11월 21일
0

algorithm

목록 보기
5/31

문제 설명

Given a positive integer n, find the pivot integer x such that:

The sum of all elements between 1 and x inclusively equals the sum of all elements between x and n inclusively.
Return the pivot integer x. If no such integer exists, return -1. It is guaranteed that there will be at most one pivot index for the given input.

제한 사항

  • 1 <= n <= 1000

입출력 예

내 풀이

/**
 * @param {number} n
 * @return {number}
 */

const check = (mid, n) => {
    let sum1 = 0;
    let sum2 = 0;
    
    for (let i = 0; i <= mid; i++) {
        sum1 += i
    }

    for (let i = mid; i <= n; i++) {
        sum2 += i
    }

    return sum1 === sum2 ? 0 : sum1 > sum2 ? 1 : -1
};

const pivotInteger = function(n) {
    let lt = 0;
    let rt = n;

    while (lt <= rt) {
        let mid = Math.floor((lt + rt) / 2);
        let value = check(mid, n);
        if (value === 0) return mid
        if (value === 1) rt = mid -1
        if (value === -1) lt = mid + 1 
    }

    return -1
};

회고

1부터 n까지 숫자들 중 이진탐색을 통해 중간 분기점을 찾아 풀어버렸다..!

profile
안녕하세여

0개의 댓글