leetcode practice - python3 (7)

48 篇文章 0 订阅
15 篇文章 0 订阅

543. Diameter of Binary Tree

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.

思路:维护当前最大值,dfs求左右子树的高度,若和大于当前最大值,更新最大值。

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

class Solution:
    def diameterOfBinaryTree(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def solve(r):
            if r == None:
                return 0

            hl = solve(r.left)
            hr = solve(r.right)

            if hl + hr > ans[0]:
                ans[0] = hl + hr

            if hl > hr:
                return hl + 1
            return hr + 1

        ans = [0]
        solve(root)
        return ans[0]

Beat 99.32% python3 2018-05-23

461. Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:
0 ≤ x, y < 231.

Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑

The above arrows point to positions where the corresponding bits are different.

思路:求异或,数下二进制表示中1的个数

class Solution:
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        t = x ^ y
        b = 1
        ans = 0
        for i in range(32):
            if t & b:
                ans += 1
            b <<= 1

        return ans

Beat 91.25% python3 2018-05-23

优化:不遍历所有32个bit位

class Solution:
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        t = x ^ y
        ans = 0
        while t:
            ans += 1
            t &= t-1

        return ans

Beat 91.25% python3 2018-05-23

优化:不使用新遍量

class Solution:
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        y = x ^ y
        x = 0
        while y:
            x += 1
            y &= y-1

        return x

Beat 91.25% python3 2018-05-23

class Solution:
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        x = x ^ y 
        y = 0
        while x > 0:
            y += x & 1
            x >>= 1
        return y

Beat 100.0% python3 2018-05-23
注:多次运行时间不同

136. Single Number

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:
Input: [2,2,1]
Output: 1

Example 2:
Input: [4,1,2,1,2]
Output: 4

思路:异或

class Solution:
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        ans = 0
        for n in nums:
            ans ^= n
        return ans

Beat 99.78% python3 2018-05-24

141. Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

思路:两个指针,一个每次走一步,一个每次走两步,找到相同的则有环

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

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        first, second = head, head
        while first and second:
            first = first.next
            second = second.next
            if second:
                second = second.next
                if first == second:
                    return True
        return False

Beat 27% python 2018-05-24

优化:使用异常,减少判断

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

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        try:
            first, second = head, head.next
            while first is not second:
                first = first.next
                second = second.next.next
            return True
        except:
            return False

Beat 99.60% python 2018-05-24
注:多次运行时间不同

160. Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A: a1 → a2

c1 → c2 → c3

B: b1 → b2 → b3
begin to intersect at node c1.

Notes:
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.

思路:两个指针,一个走到尾,数处长度差,另一个继续走,同时一个指针从同一个链开头走,即找出长出来的部分。
然后找相同节点

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

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        lenA, lenB = 0, 0
        pA, pB = headA, headB

        while pA and pB:
            pA, pB = pA.next, pB.next
            lenA += 1
            lenB += 1

        p1, p2 = headA, headB
        while pA:
            pA, p1 = pA.next, p1.next
        while pB:
            pB, p2 = pB.next, p2.next

        while p1 and p2:
            if p1 is p2:
                return p1
            p1, p2 = p1.next, p2.next

        return None

sol = Solution()

a1 = ListNode('a1')
a2 = ListNode('a2')
b1 = ListNode('b1')
b2 = ListNode('b2')
b3 = ListNode('b3')
c1 = ListNode('c1')
c2 = ListNode('c2')
c3 = ListNode('c3')

a1.next = a2
a2.next = c1
b1.next = b2
b2.next = b3
b3.next = c1

c1.next = c2
c2.next = c3
print(sol.getIntersectionNode(a1, b1).val)

Beat 99.91% python 2018-05-25
注:多次运行时间不同

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值