def get_max_one(A):
A = [str(i) for i in A]
s1 = ‘‘.join(A) #我想把列表变成字符串,然后按0 split ,列表里必须都是字符串
A = s1.split(‘0‘)
num = max([len(i) for i in A])
return num
def get_list(self, a, k):
li = []
n = 0
m = k
while 1:
l1 = a[n:m - 1]
for j in range(m - 1, len(a)):
l1.append(a[j])
li.append(l1)
l1 = a[n:m - 1]
n = n + 1
m = n + k
if m > len(a):
return li #这个函数是 返回所有的情况,假如[1,2,3] 根据 K,假如就是2
只要取1,2 1,3 2,3 一次类推
现在只要获取到为0的下标,调用上述函数,就能返回所有结果
def longestOnes(A, K):
zero_num = []
for i in range(len(A)):
if A[i] == 0:
zero_num.append(i)
all_case = get_list(zero_num, K)
print(all_case) #所有情况
max_len = 0 #每次和这个比较,长的就放在这
for case in all_case:
a = A.copy()
for num in case:
a[num] = 1
max_len1 = get_max_one(a) # type: int get_max_one(a)为上文的获取最大值的函数
if max_len1 > max_len:
max_len = max_len1
class Solution:
def longestOnes(self, A, K):
zero_num = []
max_len = 0
for i in range(len(A)):
if A[i] == 0:
zero_num.append(i)
all_case = self.get_list(zero_num, K)
print(all_case)
for case in all_case:
a = A.copy()
for num in case:
a[num] = 1
max_len1 = self.get_max_one(a) # type: int
if max_len1 > max_len:
max_len = max_len1
print(A)
return max_len
def get_max_one(self, A):
A = [str(i) for i in A]
s1 = ‘‘.join(A)
A = s1.split(‘0‘)
num = max([len(i) for i in A])
return num
def get_list(self, a, k):
li = []
n = 0
m = k
while 1:
l1 = a[n:m - 1]
for j in range(m - 1, len(a)):
l1.append(a[j])
li.append(l1)
l1 = a[n:m - 1]
n = n + 1
m = n + k
if m > len(a):
return li
1. ‘’.join(list) 时,必须要时list里都是字符串才可以
2. a = [1,2,3]
b = a
b[0] = 111
a 也会变,由于时指向同一个内存地址,用浅copy就以了
3. 没有考虑优化,我太难了
原文:https://www.cnblogs.com/liqiangwei/p/14418818.html