摘要:復(fù)雜度思路找數(shù)組里面的等差數(shù)列的個數(shù)。想法是如果一開始三個數(shù)就滿足是等差數(shù)列的話,就在當(dāng)前已有的數(shù)目上不斷的累加的結(jié)果。
Leetcode[413] Arithmetic Slices
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.
A = [1, 2, 3, 4] return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itselfDP
復(fù)雜度
O(N)
思路
找數(shù)組里面的等差數(shù)列的個數(shù)。想法是如果一開始三個數(shù)就滿足是等差數(shù)列的話,就在當(dāng)前已有的數(shù)目上不斷的累加count的結(jié)果。然后更新sum。
代碼
public int numberOfArithmeticSlices(int[] nums) { int cur = 0, sum = 0; for(int i = 2; i < nums.length; i ++) { if(nums[i] == nums[i - 1] && nums[i - 1] == nums[i - 1]) { cur += 1; sum += cur; } else { cur = 0; } } return sum; }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/69792.html
摘要:題目要求將包含大于等于三個元素且任意相鄰兩個元素之間的差相等的數(shù)組成為等差數(shù)列。現(xiàn)在輸入一個隨機(jī)數(shù)組,問該數(shù)組中一共可以找出多少組等差數(shù)列。 題目要求 A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any ...
摘要:這個題沒什么好說的,用棧就可以了,注意一下兩個數(shù)計算的時候誰前誰后就行了。 Evaluate Reverse Polish Notation https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/ Evaluate the value of an arithmetic expression in Reve...
Problem Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Note: Division between two inte...
摘要:棧法復(fù)雜度時間空間思路逆波蘭表達(dá)式的計算十分方便,對于運算符,其運算的兩個數(shù)就是這個運算符前面的兩個數(shù)。注意對于減法,先彈出的是減號后面的數(shù)。 Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operato...
摘要:我們一般看到的數(shù)學(xué)表達(dá)式就是中綴表達(dá)式,也就是將符號放在兩個數(shù)字之間。后綴表達(dá)式也就是將運算符放在相應(yīng)數(shù)字的后面。后綴表達(dá)式相當(dāng)于樹中的后序遍歷。通過獲得對應(yīng)位置的操作符。如果對應(yīng)的還是操作符,則繼續(xù)遞歸往前計算。 題目要求 Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid...
閱讀 2003·2021-08-11 11:13
閱讀 1027·2021-07-25 21:37
閱讀 2583·2019-08-29 18:42
閱讀 2516·2019-08-26 12:18
閱讀 921·2019-08-26 11:29
閱讀 1695·2019-08-23 17:17
閱讀 2670·2019-08-23 15:55
閱讀 2612·2019-08-23 14:34