본문으로 바로가기

Description

정수 배열은 적어도 세 개의 원소로 구성되어 있고 연속된 두 원소의 차이가 같으면 산술이라고 할때 정수 배열 num이 지정되면 num의 산술 하위 배열 수를 반환하는 문제입니다.

An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

  • For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.

Given an integer array nums, return the number of arithmetic subarrays of nums.

subarray is a contiguous subsequence of the array.

Example 1:

Input: nums = [1,2,3,4]
Output: 3
Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.

Example 2:

Input: nums = [1]
Output: 0

Solution 1. 반복

public int numberOfArithmeticSlices(int[] nums) {
    int len = nums.length;
    int cnt = 0;
    int sum = 0;
    for (int i = 2; i < len; i++) {
        if(nums[i-1]-nums[i-2] == nums[i]-nums[i-1]){
            cnt++;
            sum += cnt;
        }else{
            cnt=0;
        }
    }
    return sum;
}

3번째 요소부터 반복하며 연속된 요소일경우 카운트를 하며 이전 요소와도 연속된 관계에 대한 갯수를 함께 더해나갑니다.

Reference

 

Arithmetic Slices - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com