?LeetCode刷題實戰(zhàn)413:等差數(shù)列劃分
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.
A subarray is a contiguous subsequence of the array.
示例
示例 1:
輸入:nums = [1,2,3,4]
輸出:3
解釋:nums 中有三個子等差數(shù)組:[1, 2, 3]、[2, 3, 4] 和 [1,2,3,4] 自身。
示例 2:
輸入:nums = [1]
輸出:0
解題
長度為n的等差數(shù)列中,自身以及它的子集,個數(shù)一共有(n-1)*(n-2)/2。
dx為等差數(shù)列中兩個相鄰元素的差的絕對值。數(shù)組中兩個dx不想等的等差數(shù)列最多可能有一個重復使用的點。例如1,2,3,6,9。3即使那個重復的值,分別是1,2,3的尾,以及3,6,9的頭。
class?Solution?{
public:
????#define?numberOfNsize(x) (((x-1)*(x-2))>>1)
????int?numberOfArithmeticSlices(vector<int>& A)?{
????????//存儲A中出現(xiàn)過的連續(xù)的等差數(shù)列的最長長度
????????int?size = A.size();
????????int?pos = 0;
????????int?res = 0;
????????while?(pos < size-2) {
???????????//試圖從pos往后查詢一個等差數(shù)列
????????????int?dx = A[pos + 1] - A[pos];
????????????int?next = pos + 1;
????????????while?((next-1] == dx)) {
????????????????next++;
????????????}
????????????int?length = next - pos;
????????????pos = next-1;
????????????if?(length >= 3) res += numberOfNsize(length);
????????}
????????return?res;
????}
};
LeetCode刷題實戰(zhàn)402:移掉 K 位數(shù)字
LeetCode刷題實戰(zhàn)405:數(shù)字轉換為十六進制數(shù)
LeetCode刷題實戰(zhàn)406:根據(jù)身高重建隊列
LeetCode刷題實戰(zhàn)410:分割數(shù)組的最大值
LeetCode刷題實戰(zhàn)411:最短獨占單詞縮寫
LeetCode刷題實戰(zhàn)412:Fizz Buzz
