Post

[Programmers] #120923 - 연속된 수의 합 [Java][C++][Python]

[Programmers] #120923 - 연속된 수의 합 [Java][C++][Python]

문제 링크


1. 아이디어

연속된 num개의 수의 합이 total이 될 때 원래 수열을 구하는 문제로 등차수열의 합 공식을 응용하면 해결할 수 있다. 등차수열의 초항을 $a$, 공차를 $d$라고 할 때, $total = \dfrac{(a + a + (num - 1) \times d) \times num}{2}$이고 연속된 정수라서 공차가 1이므로, 식을 정리하면 $a = \dfrac{total}{num} - \dfrac{num - 1}{2}$가 된다.


2. 복잡도

접근시간공간
풀이$O(N)$$O(N)$

($N$ = num)


3. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
class Solution {
    public int[] solution(int num, int total) {
        int[] arr = new int[num];
        int a = total / num - (num - 1) / 2;
        for (int i = 0; i < num; i++) {
            arr[i] = a + i;
        }

        return arr;
    }
}
1
2
3
4
5
6
7
8
#include <bits/stdc++.h>
using namespace std;

vector<int> solution(int num, int total) {
    vector<int> v(num);
    iota(v.begin(), v.end(), total / num - (num - 1) / 2);
    return v;
}
1
2
3
def solution(num, total):
    a = total // num - (num - 1) // 2
    return list(range(a, a + num))

This post is licensed under CC BY 4.0 by the author.