python_lintcode_96. 鏈表劃分_389. 判斷數獨是否合法

來源:互聯網
上載者:User
96. 鏈表劃分 題目

給定一個單鏈表和數值x,劃分鏈表使得所有小於x的節點排在大於等於x的節點之前。

你應該保留兩部分內鏈表節點原有的相對順序。

範例

給定鏈表 1->4->3->2->5->2->null,並且 x=3返回 1->2->2->4->3->5->null
思路 簡單思路:就是建立兩條鏈表分別儲存小於x的和大於x的,然後在將兩條鏈表進行合并即可。 代碼
"""Definition of ListNodeclass ListNode(object):    def __init__(self, val, next=None):        self.val = val        self.next = next"""class Solution:    """    @param: head: The first node of linked list    @param: x: An integer    @return: A ListNode    """    def partition(self, head, x):        # write your code here        if head is None:return None        #建立兩個鏈表存放小於x和大於x        l1 = head        l2= ListNode(0)        y = l2        l3 = ListNode(0)        z = l3        while l1 :            if l1.val<x:                y.next = l1                y = y.next            else:                z.next = l1                z = z.next            l1 = l1.next        #將大於x的尾部添加None        z.next = None        #將兩條鏈表進行合并        y.next = l3.next        #返回該鏈表        return l2.next
389. 判斷數獨是否合法 題目

http://www.lintcode.com/zh-cn/problem/valid-sudoku/

請判定一個數獨是否有效。

該數獨可能只填充了部分數字,其中缺少的數字用 . 表示。

注意事項

一個合法的數獨(僅部分填充)並不一定是可解的。我們僅需使填充的空格有效即可。 思路 一開始以為是要判斷能不能可解的數獨,後面看到注意事項。 只需要判斷行列和小正方形能夠合法即可(沒有出現重複數字情況) 代碼

class Solution:    """    @param: board: the board    @return: whether the Sudoku is valid    """    def isValidSudoku(self, board):        # write your code here        res = set()        res2 =set()        #1判斷行列有效        for i in range(9):            for j in range(9):            #行                if board[i][j]!='.' and board[i][j] in res:                    return False                else:                    res.add(board[i][j])            #列                if board[j][i]!='.' and board[j][i] in res2:                    return False                else:                    res2.add(board[j][i])            res2.clear()            res.clear()        #2判斷每一塊有效            #對於九大塊        for i in range(0,9,3):            for j in range(0,9,3):                #對於九大塊內的一小塊                for a in range(i,i+3):                    for b in range(j,j+3):                        #判斷是否有效                        if board[a][b]!='.' and board[a][b] in res:                            return False                        else:                            res.add(board[a][b])                #小塊判斷完即可清空res                res.clear()        return True

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.