41、二位数组中的查找
比较简单
# -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
height = len(array)
length = len(array[0])
i = length - 1
j = 0
while i >= 0 and j <= height:
if array[j][i] == target:
return True
elif array[j][i] > target:
i -= 1
elif array[j][i] < target:
j += 1
return False
42、扑克牌顺子
我的想法是如果数组除了0无重复元素,且除去0的最大值减最小值小于等于4的话那么就返回True。
# -*- coding:utf-8 -*-
class Solution:
def IsContinuous(self, numbers):
# write code here
if not numbers:
return False
numbers.sort()
cur_min = 13
cur_max = 0
temp = 0
for i in numbers:
if i != 0:
if i == temp:
return False
temp = i
if i < cur_min:
cur_min = i
if i > cur_max:
cur_max = i
return cur_max-cur_min<=4
43、孩子们的游戏
自己用循环写的,调试了很久= =。
class Solution:
def LastRemaining_Solution(self, n, m):
# write code here
temp = list(range(n))
cur = -1
index = -1
while len(temp) > 1:
cur += 1
index += 1
index = index if index < len(temp) else 0
if cur == m-1:
cur = -1
temp.remove(temp[index])
index -= 1
return temp[0]
后来看别人的解法发现了这种问题有个专门的名词:约瑟夫环问题。仔细琢磨了一下,博客地址:https://www.cnblogs.com/cmmdc/p/7216726.html
结论:f[n] = (f[n-1] + m)%n
约瑟夫环代码
class Solution:
def LastRemaining_Solution(self, n, m):
# write code here
if n == 1:
return 0
memory = [0]
for i in range(2, n+1):
memory.append((memory[-1] + m)%i)
return memory[-1]
44、正则表达式匹配
分好情况,一类一类写就可以了,花了挺长时间,还是没写出来。先马住
45、表示数值的字符串
class Solution:
def isNumeric(self, s):
isAllowDot = True
isAllowE = True
for i in range(len(s)):
if s[i] in "+-" and (i == 0 or s[i - 1] in "eE") and i < len(s) - 1:
continue
elif isAllowDot and s[i] == ".":
isAllowDot = False
if i >= len(s) - 1 or s[i + 1] not in "0123456789":
return False
elif isAllowE and s[i] in "Ee":
isAllowDot = False
isAllowE = False
if i >= len(s) - 1 or s[i + 1] not in "0123456789+-":
return False
elif s[i] not in "0123456789":
return False
return True