1. 程式人生 > >第一遍怒刷漢化版LEETCODE leetcode,PYTHON題答案,應用的是python2

第一遍怒刷漢化版LEETCODE leetcode,PYTHON題答案,應用的是python2

在此記錄自己做的所有PYTHON題的答案,我用的PY2。
更新的慢。畢竟腦子笨,比如其中range可以換成xrange

1.從排序陣列中刪除重複項

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """

        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if
nums[i] == nums[i+1]: del nums[i+1] else: break return len(nums)

買賣股票的最佳時機 II

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        zong = 0
        for
i in range(len(prices)-1): if prices[i+1]>prices[i]: zong+= (prices[i+1]-prices[i]) return zong

給定一個數組,將陣列中的元素向右移動 k 個位置,其中 k 是非負數。

class Solution(object):
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: void Do not return anything, modify nums in-place instead.
        """
k = k%len(nums) nums[:] = nums[-k:]+nums[:-k]

給定一個整數陣列,判斷是否存在重複元素。
如果任何值在陣列中出現至少兩次,函式返回 true。如果陣列中每個元素都不相同,則返回 false。

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if len(set(nums)) == len(nums):
            return False
        else:
            return True

給定一個非空整數陣列,除了某個元素只出現一次以外,其餘每個元素均出現兩次。找出那個只出現了一次的元素

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        for i in range(len(nums)):
            if len(nums) == 1:
                return nums[0]
            if nums[0] == nums[1]:
                del nums[0]
                del nums[0]
            else:
                return nums[0]

給定一個非負整陣列成的非空陣列,在該數的基礎上加一,返回一個新的陣列。

class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        num = 1
        for i in range(len(digits)):
            num+=int(digits[i])*(10**(len(digits)-i-1))

        return [int(i) for i in list(str(num))]

給定一個數組 nums,編寫一個函式將所有 0 移動到陣列的末尾,同時保持非零元素的相對順序

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        j=0
        for i in xrange(len(nums)):
            if nums[j] == 0:
                nums.append(nums.pop(j))

            else:
                j+=1

給定一個整數陣列和一個目標值,找出陣列中和為目標值的兩個數。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in xrange(len(nums)):
            for j in xrange(i+1,len(nums)):
                if nums[i]+nums[j] == target:
                    return [i,j]

判斷一個 9x9 的數獨是否有效。只需要根據以下規則,驗證已經填入的數字是否有效即可。

class Solution(object):
    def isValidSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """
        for i in xrange(9):
            hang = board[i]
            lie = []
            for j in range(9):
                lie.append(board[j][i])
            for m in hang:
                if hang.count(m)>1 and m!='.':
                    return False
            for n in lie:
                if lie.count(n)>1 and n!='.':
                    return False
            for j in xrange(9):
                if i%3==0 and j%3==0:
                    small = []
                    for p in range(i,i+3):
                        for q in range(j,j+3):
                            if board[p][q] != '.':
                                small.append(board[p][q])
                    if len(small) != len(list(set(small))):
                        print i,j,p,q
                        return False
        return True

給定一個 n × n 的二維矩陣表示一個影象。

將影象順時針旋轉 90 度。

class Solution(object):
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        n = len(matrix)
        for i in range(n/2):
            for j in range(i,n-i-1):
                tmp = matrix[i][j]
                print tmp
                matrix[i][j]=matrix[n-j-1][i]
                matrix[j][n-i-1],tmp = tmp,matrix[j][n-i-1]
                matrix[n-i-1][n-j-1],tmp = tmp,matrix[n-i-1][n-j-1]
                matrix[n-j-1][i]=tmp

請編寫一個函式,其功能是將輸入的字串反轉過來。

class Solution(object):
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        return str(s)[::-1]

顛倒整數

class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """

        if str(x)[0] == '-':
            num = int('-'+str(x)[1:][::-1])
        else :
            num = int(str(x)[::-1])

        if num>2**31-1 or num<-2**31:
            return 0
        else:
            return num

給定一個字串,找到它的第一個不重複的字元,並返回它的索引。如果不存在,則返回 -1。

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        for i in range(len(s)):
            if s[i] not in s[i+1:] and s[i] not in s[:i]:
                return i
        return -1

有效的字母異位詞

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """

        if len(s) != len(t):
            return False
        while s:
            tmp = s[0]
            s=s.replace(tmp,'')
            t=t.replace(tmp,'')
            if len(s)!=len(t):
                return False
        return True

給定一個字串,驗證它是否是迴文串,只考慮字母和數字字元,可以忽略字母的大小寫。

class Solution(object):
    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        s =  filter(str.isalnum, str(s)).lower()

        if s == s[::-1]:

            return True
        else:
            return False

報數序列是指一個整數序列,按照其中的整數的順序進行報數,得到下一個數。其前五項如下:

class Solution(object):
    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        old = '1'
        for i in range(n-1):
            num = 1
            value = ''
            next = ''
            while 1:
                try:
                    if old[0]==old[1]:
                        num += 1
                        value = old[0]
                    else:
                        if value!='':
                            next+= str(num)+str(value)
                        else:
                            next+= str(num)+str(old[0])
                        num = 1
                        value = ''
                    old=old[1:]
                except IndexError,e:
                    next += str(num)+str(old[0])
                    old = next
                    break
        return old

編寫一個函式來查詢字串陣列中的最長公共字首。

如果不存在公共字首,返回空字串 “”。

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        rstr = ''
        if strs == []:
            return rstr

        old = strs[0]
        for i in range(len(old)): #i為第一個元素的遍歷單個字元
            for j in range(len(strs)):
                try:
                    if old[i] == strs[j][i]:
                        pass
                    else:
                        return rstr
                except:
                    return rstr
            else:
                rstr += old[i]
        return rstr

請編寫一個函式,使其可以刪除某個連結串列中給定的(非末尾)節點,你將只被給定要求被刪除的節點。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        node.val = node.next.val
        node.next = node.next.next

給定一個連結串列,刪除連結串列的倒數第 n 個節點,並且返回連結串列的頭結點。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """

        dummy = ListNode(-1)
        dummy.next = head
        p = dummy
        c = head
        c2 = head
        num = 0
        while c2 is not None:
            num+=1
            c2=c2.next
        for i in range(num-n+1):
            if c.next is not None:
                p=p.next
                c=c.next
            else:
                p.next = None
                return dummy.next  
        p.val = c.val
        p.next=c.next
        return dummy.next

反轉連結串列

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        p = head
        q = None
        while p:
            c = p.next
            p.next = q
            q = p
            p = c
        return q

將兩個有序連結串列合併為一個新的有序連結串列並返回。新連結串列是通過拼接給定的兩個連結串列的所有節點組成的。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if l1==None and l2==None:
            return None
        if l1==None:
            return l2
        if l2==None:
            return l1
        if l1.val<l2.val:
            l1.next = self.mergeTwoLists(l1.next,l2)
            return l1
        if l2.val<l1.val:
            l2.next = self.mergeTwoLists(l1,l2.next)
            return l2
        elif l1.val==l2.val:
            l1.next = self.mergeTwoLists(l1.next,l2)
            return l1

請判斷一個連結串列是否為迴文連結串列。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        list1 = []
        list2 = []
        if head == None:
            return True
        while head:
            list1.append(head.val)
            list2.append(head.val)
            head = head.next
        list1.reverse()
        if list1 == list2:
            return True
        else:
            return False

給定一個連結串列,判斷連結串列中是否有環。

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head == None:
            return False
        try:
            p1 =head 
            p2 = head.next
        except:
            return False
        while p1:
            if p1 == p2:
                return True
            else:
                try:
                    p1 =p1.next
                    p2 = p2.next
                    p2 = p2 .next
                except:
                    return False
        return False

二叉樹的最大深度

class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root == None:
            return 0
        else:
            return 1+max(self.maxDepth(root.left),self.maxDepth(root.right))