摘要:復(fù)雜度思路找數(shù)組里面的等差數(shù)列的個(gè)數(shù)。想法是如果一開始三個(gè)數(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ù)列的個(gè)數(shù)。想法是如果一開始三個(gè)數(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)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/69792.html
摘要:題目要求將包含大于等于三個(gè)元素且任意相鄰兩個(gè)元素之間的差相等的數(shù)組成為等差數(shù)列。現(xiàn)在輸入一個(gè)隨機(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 ...
摘要:這個(gè)題沒什么好說的,用棧就可以了,注意一下兩個(gè)數(shù)計(jì)算的時(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ù)雜度時(shí)間空間思路逆波蘭表達(dá)式的計(jì)算十分方便,對(duì)于運(yùn)算符,其運(yùn)算的兩個(gè)數(shù)就是這個(gè)運(yùn)算符前面的兩個(gè)數(shù)。注意對(duì)于減法,先彈出的是減號(hào)后面的數(shù)。 Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operato...
摘要:我們一般看到的數(shù)學(xué)表達(dá)式就是中綴表達(dá)式,也就是將符號(hào)放在兩個(gè)數(shù)字之間。后綴表達(dá)式也就是將運(yùn)算符放在相應(yīng)數(shù)字的后面。后綴表達(dá)式相當(dāng)于樹中的后序遍歷。通過獲得對(duì)應(yīng)位置的操作符。如果對(duì)應(yīng)的還是操作符,則繼續(xù)遞歸往前計(jì)算。 題目要求 Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid...
閱讀 2005·2021-08-11 11:13
閱讀 1028·2021-07-25 21:37
閱讀 2583·2019-08-29 18:42
閱讀 2519·2019-08-26 12:18
閱讀 924·2019-08-26 11:29
閱讀 1697·2019-08-23 17:17
閱讀 2672·2019-08-23 15:55
閱讀 2615·2019-08-23 14:34