41-45題

41、二位數(shù)組中的查找
比較簡單

# -*- 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、撲克牌順子
我的想法是如果數(shù)組除了0無重復(fù)元素,且除去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、孩子們的游戲
自己用循環(huán)寫的,調(diào)試了很久= =。

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]

后來看別人的解法發(fā)現(xiàn)了這種問題有個專門的名詞:約瑟夫環(huán)問題。仔細(xì)琢磨了一下,博客地址:https://www.cnblogs.com/cmmdc/p/7216726.html
結(jié)論:f[n] = (f[n-1] + m)%n
約瑟夫環(huá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、正則表達(dá)式匹配
分好情況,一類一類寫就可以了,花了挺長時間,還是沒寫出來。先馬住

45、表示數(shù)值的字符串

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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容