“This is my 37th day of participating in the First Challenge 2022. For details: First Challenge 2022”

preface

This is the second question in LeetCode’s Biweekly Contest 72 for Medium, which examines the basic equations of mathematics. It’s easy to use mathematical ideas, and to complicate simple problems with other solutions.

describe

Given an integer num, return three consecutive integers (as a sorted array) that sum to num. If num cannot be expressed as the sum of three consecutive integers, return an empty array.

Example 1:

Output: [10,11,12] Explanation: 33 can be expressed as 10 + 11 + 12 = 33. 10, 11, 12 are 3 consecutive integers, so we return [10, 11, 12].Copy the code

Example 2:

Input: num = 4
Output: []
Explanation: There is no way to express 4 as the sum of 3 consecutive integers.
Copy the code

Note:

0 <= num <= 10^15
Copy the code

parsing

Given an integer num, return three consecutive integer results that sum to num. If num cannot be represented as the sum of three consecutive integers, an empty array is returned.

The questions are also simple and clear. I like the simple and clear style of the questions in the competition. I get annoyed when I see those long-winded questions that are not clear.

So we can use the equation method. If the smallest of the three numbers is x, then the sum of the three numbers is num, then we can write the equation

x + x + 1 + x + 2 = num
Copy the code

Solve this equation and find the value of x is zero

x = num/3 - 1
Copy the code

If num cannot be divisible by 3, there must be no solution. Return the empty list directly. Otherwise, return the list formed by three integers directly according to the solution result.

answer

class Solution(object): def sumOfThree(self, num): """ :type num: int :rtype: List[int] """ if num%3! =0: return [] a = num//3 - 1 b = a + 1 c = b + 1 return [a,b,c]Copy the code

The results

379/379 Test cases passed. Status: Accepted Runtime: 24 MS Memory Usage: 13.4 MBCopy the code

The original link

Leetcode.com/contest/biw…

Your support is my biggest motivation