Given an integer num, return _three consecutive integers (as a sorted array)__thatsum to _num. If num cannot be expressed as the sum of three consecutive integers, return anempty array.
Let the three consecutive integers be x, x+1, x+2. Their sum is 3x+3. So, num = 3x+3 ⇒ x = (num-3)//3. If num is not divisible by 3, there is no solution.
classSolution {
publiclong[]sumOfThree(long num) {
if (num % 3 != 0) returnnewlong[0];
long x = num / 3 - 1;
returnnewlong[]{x, x + 1, x + 2};
}
}
1
2
3
4
5
6
7
classSolution {
funsumOfThree(num: Long): LongArray {
if (num % 3L!=0L) return longArrayOf()
val x = num / 3 - 1return longArrayOf(x, x + 1, x + 2)
}
}
1
2
3
4
5
6
classSolution:
defsumOfThree(self, num: int) -> list[int]:
if num %3!=0:
return []
x = num //3-1return [x, x +1, x +2]
1
2
3
4
5
6
7
impl Solution {
pubfnsum_of_three(num: i64) -> Vec<i64> {
if num %3!=0 { returnvec![]; }
let x = num /3-1;
vec![x, x +1, x +2]
}
}