Leet Code OJ 簡單(三)

58.最後一個單詞的長度  52ms

class Solution:
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        s = s.split(' ')
        while "" in s:
            s.remove("")
        if not s:
            return 0
        return len(s[-1])

66.加一 56ms

class Solution:
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        sum = 0
        r = []
        for index, i in enumerate(digits):
            sum += i*pow(10,len(digits)-index-1)
        sum += 1
        while sum:
            i = 1
            r.append(sum % pow(10,i))
            sum = sum // pow(10,i)
            i += 1

        r.reverse()
        return r

67.二進制求和 60ms

class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        return (bin(int(a, 2) + int(b, 2))[2:])

69.x的平方根 76ms    擊敗了81.06% 的用戶

class Solution:
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        return int(pow(x, 0.5))

83.刪除排序鏈表重複元素  76ms  擊敗了48.84% 的用戶

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

class Solution:
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return None
        cur = head
        while cur.next:
            if cur.val == cur.next.val:
                if cur.next.next:
                    t = cur.next.next
                    cur.next = t
                else:
                    cur.next = None
            else:
                cur = cur.next
        return head

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章