Skip to content

Commit 78dcd51

Browse files
committed
413. Arithmetic Slices
1 parent b6e1ba9 commit 78dcd51

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
3+
1. 아이디어 : 등차수열의 모든 부분배열을 구하므로, 각 원소를 차례대로 완전탐색하며 3개 이상의 원소가 차이가 같은지 확인
4+
같을 경우, 미리 구해둔 경우의 수로 계산해준다.
5+
6+
2. 시간복잡도 : O(2N)
7+
8+
3. 자료구조/알고리즘 : 누적합, 완전탐색
9+
10+
*/
11+
12+
class Solution {
13+
public int numberOfArithmeticSlices(int[] nums) {
14+
// 모든 등차수열 구하기
15+
// 최소 3개의 원소
16+
17+
// 1 2 3 5 7 10 13 17 21 25
18+
19+
if(nums.length < 3) return 0;
20+
21+
int ans = 0;
22+
int cnt = 2;
23+
int diff = nums[1] - nums[0];
24+
25+
int[] sum = new int[nums.length+1];
26+
for(int i=3; i<=nums.length; i++) {
27+
sum[i] = sum[i-1] + (i-2);
28+
}
29+
30+
for(int i=2; i<nums.length; i++) {
31+
if((nums[i] - nums[i-1]) != diff) {
32+
ans+=sum[cnt];
33+
cnt = 2;
34+
diff = nums[i] - nums[i-1];
35+
}
36+
else cnt++;
37+
}
38+
39+
if(cnt > 2) {
40+
ans+=sum[cnt];
41+
}
42+
43+
return ans;
44+
}
45+
}

0 commit comments

Comments
 (0)