本文主要是介绍码蹄集丨等差,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目来源:码蹄集
题目介绍:
B站老师思路讲解:https://www.bilibili.com/video/BV1vY411B7jg/?t=1958.7&vd_source=3ae2a916df1bc5c1114c2bf3e95a2118
Python代码实现:
参考链接:https://blog.51cto.com/u_15745546/5950627
def main():#code herearr = list(map(int,input().split()))n = len(arr)dp = [0]*nfor i in range(2,n):if arr[i]-arr[i-1] == arr[i-1]-arr[i-2]:if dp[i-1] != 0:dp[i] = dp[i-1] +1else:dp[i] = 3tot = 0for i in range(2,n):if dp[i] >= 3:tot += dp[i]-3+1print(tot)if __name__ == '__main__':main();
提交测试结果:
C++代码实现:
#include <iostream>
#include <vector>using namespace std;int main() {vector<int> arr;int num;while (cin >> num) {arr.push_back(num);}int n = arr.size();vector<int> dp(n, 0);for (int i = 2; i < n; i++) {if (arr[i] - arr[i - 1] == arr[i - 1] - arr[i - 2]) {if (dp[i - 1] != 0) {dp[i] = dp[i - 1] + 1;} else {dp[i] = 3;}}}int tot = 0;for (int i = 2; i < n; i++) {if (dp[i] >= 3) {tot += dp[i] - 3 + 1;}}cout << tot << endl;return 0;
}
提交测试结果:
Java代码实现:
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);String[] input = sc.nextLine().split(" ");int[] arr = new int[input.length];for (int i = 0; i < input.length; i++) {arr[i] = Integer.parseInt(input[i]);}int n = arr.length;int[] dp = new int[n];for (int i = 2; i < n; i++) {if (arr[i] - arr[i - 1] == arr[i - 1] - arr[i - 2]) {if (dp[i - 1] != 0) {dp[i] = dp[i - 1] + 1;} else {dp[i] = 3;}}}int tot = 0;for (int i = 2; i < n; i++) {if (dp[i] >= 3) {tot += dp[i] - 3 + 1;}}System.out.println(tot);sc.close();}
}
提交测试结果:
这篇关于码蹄集丨等差的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!