我正在尝试在Swift 3中解决codility.com上的Flags问题,以下代码只获得6%。分数低的原因是b / c我的代码不考虑其他可能的数组,只是问题中给出的数组。必须有一种方法可以使用" for循环"而不是多个" if语句"走向最底层。任何建议或建设性的批评将不胜感激。感谢。
import Foundation
var A = [1, 5, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2]
public func solution(_ A : inout [Int]) -> Int {
let n = A.count
if n < 3 { // if there are only two elements in array A, then there are no peaks
return 0
}
var peaks = [Int]()
for i in 1..<n - 1 { // loop to find peak indices
if A[i - 1] < A[i] && A[i] > A[i + 1] {
peaks.append(i)
}
}
var numFlags = 0
if peaks[3] - peaks[2] >= peaks.count {
numFlags += 2
}
if peaks[2] - peaks[1] >= peaks.count {
numFlags += 1
}
if peaks[1] - peaks[0] >= peaks.count {
numFlags += 1
}
if peaks[2] - peaks[0] >= peaks.count {
numFlags += 1
}
return numFlags
}
print(solution(&A))
答案 0 :(得分:0)
这为Codility的Swift 3中的Flags问题提供了93%的分数。
import Foundation
var A = [1, 5, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2]
public func solution(_ A : inout [Int]) -> Int {
let n = A.count // n = number of indices in A
var peaks: [Int] = [] // create array for peaks
if n < 3 { // you need at least three elements to have a peak
return 0
}
for i in 1...n-2 { // loop to determine number of peaks and put them into peaks array
if A[i - 1] < A[i] && A[i] > A[i + 1] {
peaks.append(i)
}
}
if peaks.count == 0 {
return 0
}
var totalMarked = 0
for i in ((0 + 1)...n).reversed() {
if (i - 1) * i + 2 > n { // if this condition is met then iterate for next element
continue
}
var prevPeak = peaks.first
var marked = 1
for j in 1..<peaks.count {
if peaks[j] - prevPeak! < i { // if this condition is met then iterate for next element
continue
}
marked += 1
prevPeak = peaks[j]
if marked >= i { // if this condition is met, then exit loop
break
}
}
totalMarked = max(totalMarked, marked) // take the greater of totalMarked and marked
}
return totalMarked
}
print(solution(&A))