LeetCode - Find the pivot integer

1. Topic

2485. Find the central integer - Leetcode

Given a positive integer  , find  the pivot integern  that satisfies the following conditions  : x

  • 1x The sum of all elements between and is equal to the   sum   of all elements between and x . n

Returns the pivot integer  . Returns if no pivot integer exists   . The problem guarantees that for a given input there exists at most one pivot integer. x-1

Example 1:

Input: n = 8
 Output: 6
 Explanation: 6 is the pivot integer because 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21.

Example 2:

Input: n = 1
 Output: 1
 Explanation: 1 is the pivot integer because 1 = 1.

Example 3:

Input: n = 4
 Output: -1
 Explanation: It can be proved that there is no integer that satisfies the requirements of the topic.

hint:

  • 1 <= n <= 1000

2. Topic Interpretation

Central Integer x  :

1x The sum of all elements between and is equal to the   sum   of all elements between and x . n

We can directly calculate the sum sum=(1+n)*n/2 from 1 to n, then traverse 1 to x to calculate the sum s=(1+x)*x/2, and compare the size with sum

sum-s==s introduces √(sum)==s

That is to say, we can directly calculate whether the square root of sum is an integer to judge  the existence of the central integer x

3. Code

java

Ⅰ、

class Solution {
    public int pivotInteger(int n) {
        int sum=(n+1)*n/2;
        int s=0;
        for (int i=1;i<=n;i++){
            s+=i;
            if (s==sum){
                return i;
            }else if (s>sum)
                return -1;
            sum-=i;
        }
        return -1;
        }
}

Ⅱ、

class Solution {
    public int pivotInteger(int n) {
        int sum=(n+1)*n/2;
        int x=(int) Math.sqrt(sum);
        return x*x==sum?x:-1;
        }
}
Python

Ⅰ、

class Solution(object):
    def pivotInteger(self, n):
        Sum = n * (n + 1) / 2
        s = 0
        for i in range(n + 1):
            s += i
            if s == Sum:
                return i
            Sum -= i
        return -1

Ⅱ、

class Solution(object):
    def pivotInteger(self, n):
        s = (n * n + n) // 2
        x = int(s ** 0.5)
        if x * x == s:
            return x
        return -1

 

Guess you like

Origin blog.csdn.net/m0_63951142/article/details/131415104