[Leetcode] Running Sum of 1d Array

lkimilhol·2021년 3월 18일
0

코딩테스트

목록 보기
6/8

https://leetcode.com/problems/running-sum-of-1d-array/

Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.


배열이 주어진다면 그 배열을 순서대로 더한 새로운 배열을 저장하는 문제인데요.

[1,2,3,4] 가 주어진다면 각 자리를 더하여 [1,3,6,10]를 리턴하면 됩니다. ([1, 1+2, 1+2+3, 1+2+3+4])

아주 쉬운 문제입니다.

그냥 배열을 순회하면서 더한 값을 새로운 배열에 저장하면 됩니다.

class RunningSumOf1dArray {
    public static int[] solution(int[] nums) {
        int[] solution = new int[nums.length];
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            solution[i] = sum;
        }
        return solution;
    }
}
profile
백엔드 개발자

0개의 댓글