在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an array If it is possible, return any
If it is not possible, return Note that the entire part is used when considering what binary value it represents. For example, Example 1: Input: [1,0,1,0,1]
Output: [0,3]
Example 2: Input: [1,1,0,1,1]
Output: [-1,-1]
Note:
给定一个由 如果可以做到,请返回任何
如果无法做到,就返回 注意,在考虑每个部分所表示的二进制时,应当将其看作一个整体。例如, 示例 1: 输入:[1,0,1,0,1] 输出:[0,3] 示例 2: 输出:[1,1,0,1,1] 输出:[-1,-1] 提示:
388ms 1 class Solution { 2 func threeEqualParts(_ A: [Int]) -> [Int] { 3 var ones = [Int]() 4 for var i in 0..<A.count { 5 if A[i] == 1 { 6 ones.append(i) 7 } 8 } 9 if ones.count%3 != 0 { 10 return [-1, -1] 11 } 12 13 if ones.count == 0 { 14 return [0, A.count-1] 15 } 16 17 let part = ones.count/3 18 19 let trZero = A.count - ones.last! - 1 20 let i = ones[part-1] + trZero 21 let j = ones[part*2-1] + trZero 22 23 if i >= ones[part] { 24 return [-1, -1] 25 } 26 if j >= ones[part*2] { 27 return [-1, -1] 28 } 29 30 for var k in 0..<part { 31 let a = i - ones[k] 32 let b = j - ones[k+part] 33 let c = A.count - ones[k+part*2]-1 34 if a != b { 35 return [-1, -1] 36 } 37 if b != c { 38 return [-1, -1] 39 } 40 } 41 42 return [i, j+1] 43 } 44 } 424ms 1 class Solution { 2 func threeEqualParts(_ A: [Int]) -> [Int] { 3 let countA:Int = A.count 4 var one:Int = 0 5 for x in A {one += x} 6 if one % 3 != 0 {return [-1,-1]} 7 if one == 0 {return [0,countA - 1]} 8 one /= 3 9 var cc:Int = 0 10 var pos:[Int] = [Int](repeating: -2,count: 3) 11 var idx:Int = 0 12 for i in 0..<countA 13 { 14 if A[i] == 1 && cc % one == 0 15 { 16 pos[idx] = i 17 idx += 1 18 } 19 cc += A[i] 20 } 21 var len:Int = countA - pos[2] 22 if pos[1] < (pos[0] + len) || pos[2] < (pos[1] + len) {return [-1,-1]} 23 var i:Int = pos[0], j:Int = pos[1], k:Int = pos[2] 24 repeat 25 { 26 if (A[i] != A[j] || A[i] != A[k]) {return [-1,-1]}; 27 i += 1 28 j += 1 29 k += 1 30 }while(k < countA) 31 return [pos[0] + len - 1, pos[1] + len] 32 } 33 } 428ms 1 class Solution { 2 func threeEqualParts(_ A: [Int]) -> [Int] { 3 let countA:Int = A.count 4 var one:Int = 0 5 for x in A {one += x} 6 if one % 3 != 0 {return [-1,-1]} 7 if one == 0 {return [0,countA - 1]} 8 one /= 3 9 var cc:Int = 0 10 var pos:[Int] = [Int](repeating: -2,count: 3) 11 var idx:Int = 0 12 for i in 0..<countA 13 { 14 if A[i] == 1 && cc % one == 0 15 { 16 pos[idx] = i 17 idx += 1 18 } 19 cc += A[i] 20 } 21 var len:Int = countA - pos[2] 22 if pos[1] < (pos[0] + len) || pos[2] < (pos[1] + len) {return [-1,-1]} 23 var i:Int = pos[0], j:Int = pos[1], k:Int = pos[2] 24 repeat 25 { 26 if (A[i] != A[j] || A[i] != A[k]) {return [-1,-1]}; 27 i += 1 28 j += 1 29 k += 1 30 }while(k < countA) 31 return [pos[0] + len - 1, pos[1] + len] 32 } 33 }
|
请发表评论