Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 2485. Find the Pivot Integer

Rain Hu

2485. Find the Pivot Integer


一、題目

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

Example 1:

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. Array

int pivotInteger(int n) {
    if (n == 1) return 1;
    int right = (1 + n) * n/2;
    int left = 1;
    for (int i = 1; i < n; i++) {
        if (left == right) return i;
        left += (i+1);
        right -= i;
    }
    return -1;
}

2. Prefix Sum

int pivotInteger(int n) {
    if (n == 1) return 1;
    vector<int> presum;
    presum.push_back(0);
    for (int i = 1; i <= n; i++) {
        presum.push_back(presum.back() + i);
    }
    for (int i = 1; i < n; i++) {
        if (presum[n] - presum[i] == presum[i+1]) return i+1;
    }
    return -1;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 2486. Accept Characters to String to Make Subsequence
Next
[LeetCode] 1235. Maximum Profit in Job Scheduling