在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
(Note that B could be any subarray of A, including the entire array A.) Given an array Return Example 1: Input: [2,1,4,7,3,2,5] Output: 5 Explanation: The largest mountain is [1,4,7,3,2] which has length 5. Example 2: Input: [2,2,2] Output: 0 Explanation: There is no mountain. Note:
Follow up:
我们把数组 A 中符合下列属性的任意连续子数组 B 称为 “山脉”:
(注意:B 可以是 A 的任意子数组,包括整个数组 A。) 给出一个整数数组 如果不含有 “山脉” 则返回 示例 1: 输入:[2,1,4,7,3,2,5] 输出:5 解释:最长的 “山脉” 是 [1,4,7,3,2],长度为 5。 示例 2: 输入:[2,2,2] 输出:0 解释:不含 “山脉”。 提示:
156ms
1 class Solution { 2 func longestMountain(_ A: [Int]) -> Int { 3 var longest = 0 4 var increasing = true 5 var mountainLength = 0 6 var hasReturn = false 7 var i = 0 8 while i < A.count - 1{ 9 if increasing { 10 if A[i] < A[i+1] { 11 i += 1 12 mountainLength += 1 13 }else if A[i] > A[i+1] { 14 increasing = false 15 }else { 16 i += 1 17 mountainLength = 0 18 } 19 }else { 20 if mountainLength == 0 { 21 if A[i] >= A[i+1] { 22 i += 1 23 }else { 24 increasing = true 25 } 26 }else { 27 if A[i] > A[i+1] { 28 hasReturn = true 29 i += 1 30 mountainLength += 1 31 }else { 32 longest = max(longest, mountainLength + 1) 33 mountainLength = 0 34 increasing = false 35 } 36 } 37 } 38 } 39 if hasReturn { 40 return max(longest, mountainLength + 1) 41 }else { 42 return longest 43 } 44 } 45 } Runtime: 164 ms Memory Usage: 19.3 MB
1 class Solution { 2 func longestMountain(_ A: [Int]) -> Int { 3 var N:Int = A.count 4 var res:Int = 0 5 var up:[Int] = [Int](repeating:0,count:N) 6 var down:[Int] = [Int](repeating:0,count:N) 7 for i in stride(from:N - 2,through:0,by:-1) 8 { 9 if A[i] > A[i + 1] 10 { 11 down[i] = down[i + 1] + 1 12 } 13 } 14 for i in 0..<N 15 { 16 if i > 0 && A[i] > A[i - 1] 17 { 18 up[i] = up[i - 1] + 1 19 } 20 if up[i] > 0 && down[i] > 0 21 { 22 res = max(res, up[i] + down[i] + 1) 23 } 24 } 25 return res 26 } 27 } 168ms 1 class Solution { 2 func longestMountain(_ A: [Int]) -> Int { 3 if (A.count < 3) { 4 return 0 5 } 6 var l2r = Array(repeating: 0, count: A.count) 7 var r2l = Array(repeating: 0, count: A.count) 8 9 for i in 1..<A.count { 10 if A[i] > A[i-1] { 11 l2r[i] = l2r[i-1] + 1 12 } 13 } 14 15 for i in stride(from: A.count - 2, through: 1, by: -1) { 16 if A[i] > A[i+1] { 17 r2l[i] = r2l[i+1] + 1 18 } 19 } 20 21 var result = 0 22 for i in 1..<A.count { 23 if (l2r[i] > 0 && r2l[i] > 0) { 24 result = max(result, l2r[i] + r2l[i] + 1) 25 } 26 } 27 28 return result 29 } 30 }
|
请发表评论