zoukankan      html  css  js  c++  java
  • 653. Two Sum IV

    题目来源:
     
    自我感觉难度/真实难度:
     
    题意:
     
    分析:
     
    自己的代码:
    class Solution(object):
        def findTarget(self, root, k):
            """
            :type root: TreeNode
            :type k: int
            :rtype: bool
            """
            All=self.InOrder(root)
            Plus=[]
            #for i in range(All.size()):
            for i in range(len(All)):
                for j in range(len(All)):
                    Plus.append(All[i]+All[j])
            if k in Plus:
                return True
            return False
        
                           
        def InOrder(self,root):
            if not root:
                return
            res=[]

    res.append(root.val)
    self.InOrder(root.left) 
    self.InOrder(root.right)
    return res

    1.中序遍历不会,这不是中序遍历

    2.这样没有得到中序遍历

    代码效率/结果:
     
    优秀代码:
    # 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 findTarget(self, root, k):
            """
            :type root: TreeNode
            :type k: int
            :rtype: bool
            """
            res = self.inOrder(root)
            resset = set(res)
            for num in res:
                if k != 2 * num and k - num in resset:
                    return True
            return False
        
        def inOrder(self, root):
            if not root:
                return []
            res = []
            res.extend(self.inOrder(root.left))
            res.append(root.val)
            res.extend(self.inOrder(root.right))
            return res
    代码效率/结果:

    Runtime: 84 ms, faster than 56.86% of Python online submissions for Two Sum IV - Input is a BST.

     
    优化后的代码:
    class Solution(object):
        def findTarget(self, root, k):
            """
            :type root: TreeNode
            :type k: int
            :rtype: bool
            """
            bfs, s = [], set()
            bfs = [root]
            for i in bfs:
                if k - i.val in s:
                    return True
                s.add(i.val)
                if i.left:
                    bfs.append(i.left)
                if i.right:
                    bfs.append(i.right)
            return False

    Runtime: 108 ms, faster than 33.56% of Python online submissions for Two Sum IV - Input is a BST.

    这个时间测量是不是有问题呢?

    反思改进策略:

       1.使重复元素只有一个的办法:set()

         2.中序的过程中,一定要res.extend,不然没保存到内容

  • 相关阅读:
    微服务安全(二)OAuth 2.0
    微服务安全(一)
    Spring Security 学习+实践
    Dubbo 学习(二)服务注册与发现
    Dubbo 学习(一)
    Spring Cloud Hystrix 学习(三)请求合并
    Spring Cloud Hystrix 学习(二)熔断与降级
    Spring Cloud Hystrix 学习(一)
    Spring Cloud Gateway 学习+实践
    Spring Cloud Zuul 学习+实践
  • 原文地址:https://www.cnblogs.com/captain-dl/p/10187712.html
Copyright © 2011-2022 走看看