python学习(二十二)

注意,答案只是代表是他人写的代码,正确,但不一定能通过测试(比如超时),列举出来只是它们拥有着独到之处,虽然大部分确实比我的好

101. Symmetric Tree

题目

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.

思路与解答

感觉上确实也很简单嘛
空的居然也算镜像的

        def dfs(r1,r2):
            if r1 == r2:return True
            if r1 and r2:
                if r1.val == r2.val:
                    return dfs(r1.left,r2.right) and dfs(r1.right,r2.left)
                return False
            return False
        return dfs(root.left,root.right) if root else True

搞定

答案

差不多

        def isSym(L,R):
            if not L and not R: return True
            if L and R and L.val == R.val: 
                return isSym(L.left, R.right) and isSym(L.right, R.left)
            return False
        return isSym(root, root)

414. Third Maximum Number

题目

Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).

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

Output: 1

Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]

Output: 2

Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1]

Output: 1

Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.

思路与解答

最大数,第二最大数,第三最大数。。。

        n = sorted(set(nums))
        return n[-3] if len(n) >= 3 else n[-1]

我觉得肯定有一行的,我这个也能改一行,但是太丑了
呃,好像有时间复杂度的要求?

        fmax = smax = tmax = float('-inf')
        for n in nums :
            if n == fmax or n == smax or n <= tmax:
                continue
            if n > fmax: fmax, smax, tmax = n, fmax, smax
            elif n > smax: smax, tmax = n, smax
            elif n > tmax: tmax = n
        return tmax if tmax != float('-inf') else fmax

差不多快嘛

答案

某种答案的讨论
其它的大都差不多

669. Trim a Binary Search Tree

题目

Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.

Example 1:
Input: 

    1
   / \
  0   2

  L = 1
  R = 2

Output: 
    1
      \
       2

Example 2:
Input: 

    3
   / \
  0   4
   \
    2
   /
  1

  L = 1
  R = 3

Output: 

      3
     / 
   2   
  /
 1

思路与解答

感觉和上面的题不是一个难度的
肯定是dfs,关键要怎么做啊
我记得好像是当前节点删除后,提拔左叶节点上来,没有就右叶
不对这是个二叉搜索树,不能单纯的提拔左节点,当前值小于,所有的左边都不符合了,当前值大于同理
写者写着就失去连接了

        def dfs(r):
            if r:
                if r.val > R:
                    return dfs(r.left)
                elif r.val < L:
                    return dfs(r.right)
                else:
                    r.left = dfs(r.left)
                    r.right = dfs(r.right)
                    return r   
        return dfs(root)

很久之后才能重新连上leetcode。。。

答案

自身递归。。。一直没试过这么写
这个和我的好像啊,好像就是我的dfs函数。。。。

class Solution(object):
    def trimBST(self, root, L, R):
        """
        :type root: TreeNode
        :type L: int
        :type R: int
        :rtype: TreeNode
        """
        if not root:
            return None
        if L > root.val:
            return self.trimBST(root.right, L, R)
        elif R < root.val:
            return self.trimBST(root.left, L, R)
        root.left = self.trimBST(root.left, L, R)
        root.right = self.trimBST(root.right, L, R)
        return root

167. Two Sum II - Input array is sorted

题目

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

思路与解答

很简单
用字典吧
查一下就好
不让用相同的元素啊
是index还不是那个序号啊
居然还有重复的啊,卧槽我的设想直接崩了
这可怎么用字典啊

        d={}
        for i,j in enumerate(numbers):
            if target - j in d and d[target - j] != i:
                return [d[target - j]+1,i+1]
            d[j] = i

巧妙的避开了这个问题

答案

我有考虑过类似的方案,不过感觉不如用字典的简便

    def twoSum(self, numbers, target):
        left = 0
        right = len(numbers) - 1
        while left < right:
            sum = numbers[left] + numbers[right]
            if sum < target:
                left += 1
            elif sum > target:
                right -= 1
            else:
                return left + 1, right + 1
        return -1, -1

优秀的算法

def twoSum(self, numbers, target):
    investigatedSoFar = []
    for i in range(len(numbers)):
        if not numbers[i] in investigatedSoFar:
            investigatedSoFar.append(numbers[i])
            l, r = i + 1, len(numbers) - 1
            tmp = target - numbers[i]
            while l <= r:
                mid = l + (r-l) // 2
                if numbers[mid] == tmp:
                    return([i + 1, mid + 1])
                elif numbers[mid] < tmp:
                    l = mid + 1
                else:
                    r = mid - 1

但是大部分还是喜欢用dict的

653. Two Sum IV - Input is a BST

题目

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.

Example 1:
Input: 
    5
   / \
  3   6
 / \   \
2   4   7

Target = 9

Output: True
Example 2:
Input: 
    5
   / \
  3   6
 / \   \
2   4   7

Target = 28

Output: False

思路与解答

和上面的题差不多嘛

    def findTarget(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: bool
        """
        self.d={}
        def dfs(r):
            if r:
                if k-r.val in self.d:
                    return True
                self.d[r.val] = 1
                return dfs(r.left) or dfs(r.right)
        return bool(dfs(root))

直接return dfs(root)的话在未找到的情况先为Null而不是False,所以需要在外面增加一个bool()

答案

嗯,感觉这道题用堆栈或者队列来做是要好些,我写的时候就觉得dfs不能及时退出了

if not root:
            return False
        queue = collections.deque()
        queue.append(root)
        memo = set()
        while queue:
            node = queue.popleft()
            if k - node.val in memo:
                return True
            memo.add(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        return False

    def findTarget(self, root, k):
        if not root: return False
        bfs, s = [root], set()
        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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值