leetcode date2018/4/9

(1)

class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        seen = set()
        while n not in seen:
            seen.add(n)
            n = sum([int(x) **2 for x in str(n)])
        return n == 1

(2)

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

# solution 1
class Solution(object):
    def mergeTwoLists(self, l1, l2):
        if l1 is None or (l2 and l1.val>l2.val):
            l1, l2 = l2, l1
        tail = l1
        while tail and l2:
            if tail.next is None or (tail.next.val > l2.val):
                tail.next, l2 = l2, tail.next
            tail = tail.next
        return l1    
'''# solution 2, same as OP's solution 1
class Solution(object):
    def mergeTwoLists1(self, l1, l2):
        head = tail = ListNode(0)
        while l1 and l2:
            if l1.val<=l2.val:
                tail.next = l1
                l1 = l1.next
            else:
                tail.next = l2
                l2 = l2.next
            tail = tail.next
        tail.next = l1 if l1 else l2 # a better way is tail.next = l1 or l2, as in OP's code
        return head.next'''

(3)

class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n <= 0:
            return False

        while n % 3 == 0:            
            n = n / 3

        return True if n == 1 else False

(4)

 

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if root is None:
            return True
        stack = [(root.left, root.right)]
        while stack:
            left, right = stack.pop()
            if left is None and right is None:
                continue
            if left is None or right is None:
                return False
            if left.val == right.val:
                stack.append((left.left, right.right))
                stack.append((left.right, right.left))
            else:
                return False
        return True

 

(5) 

 

posted @ 2018-04-09 18:54  proven  阅读(119)  评论(0)    收藏  举报