1. 程式人生 > >[LeetCode] Arithmetic Slices

[LeetCode] Arithmetic Slices

body mean numbers express called its led col 數組

A sequence of number 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, these are arithmetic sequence:

1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9

The following sequence is not arithmetic.

1, 1, 2, 5, 7

A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair of integers (P, Q) such that 0 <= P < Q < N.

A slice (P, Q) of array A is called arithmetic if the sequence:
A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q.

The function should return the number of arithmetic slices in the array A.

Example:

A = [1, 2, 3, 4]

return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.

找出一個數組中的子分片並統計。

思路:也就是蠻力算法,找出每一個子分片並判斷。時間復雜度O(n^3)。

代碼中註釋了造成超時的表達式。

class Solution {
public:
    int numberOfArithmeticSlices(vector<int
>& A) { int res = 0; if (A.size() < 3) return res; for (int i = 0; i < A.size() - 2; i++) { for (int j = i + 2; j < A.size(); j++) { int cnt = 0; int tmp = A[i + 1] - A[i]; for (int k = i + 1; k <= j; k++) { /* Using this expression causes TLE if (A[k] - A[k - 1] == tmp) cnt++; */ if (A[k] - A[k - 1] != tmp) break; cnt++; } if (cnt == j - i) res++; } } return res; } }; // 84 ms

第一次使用了註釋的代碼,結果造成TLE。通過驗證得出算法沒問題,就是時間復雜度極高導致不能AC

第二次使用break提前挑出循環,減少了一丟丟計算量。成功AC

———————————————————————————————————————————————————————

通過了解蠻力算法過程,確實重復了太多次判斷,感覺使用DP也可以求解。下次想通了再更新~~

[LeetCode] Arithmetic Slices