python练习(十七)

来源:互联网 发布:volatile java 优缺点 编辑:程序博客网 时间:2024/05/22 06:15

  • Detect Capital
    • 题目
    • 思路与解答
    • 答案
  • Diameter of Binary Tree
    • 题目
    • 思路与解答
    • 答案
  • Employee Importance
    • 题目
    • 思路与解答
    • 答案
  • Factorial Trailing Zeroes
    • 题目
    • 思路与解答
    • 答案
  • Find All Numbers Disappeared in an Array
    • 题目
    • 思路与解答
    • 答案

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

520. Detect Capital

题目

Given a word, you need to judge whether the usage of capitals in it is right or not.

We define the usage of capitals in a word to be right when one of the following cases holds:

All letters in this word are capitals, like “USA”.
All letters in this word are not capitals, like “leetcode”.
Only the first letter in this word is capital if it has more than one letter, like “Google”.
Otherwise, we define that this word doesn’t use capitals in a right way.
Example 1:
Input: “USA”
Output: True
Example 2:
Input: “FlaG”
Output: False
Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.

思路与解答

先判断是不是全是大写,再判断是不是全是小写
最后判断是不是第一个是大写。。。我记得python里都有的。
好像没找到首字母大写大判断。。。那就把它变成首字母大写的与原本的比较吧。

class Solution(object):    def detectCapitalUse(self, word):        """        :type word: str        :rtype: bool        """        if word.isupper() or word.islower() or word.capitalize() == word:            return True        else:            return False

好像能改成一行的

        return True if word.isupper() or word.islower() or word.capitalize() == word else False

如果不用辅助函数的话,还是3个判断条件

        m = 0        for c in word:            if 65 <= ord(c) <= 96:                m += 1        return m == len(word) or m == 0 or (m == 1 and 65 <= ord(word[0]) <= 96)

答案

我就记得有判断首字母大写的嘛。哦,对了,不用加if也可以

return word.isupper() or word.islower() or word.istitle()

同样没找到istitle()存在写的,看起来也很厉害

return word in [word.upper(), word.lower(), word.capitalize()]

不借助辅助函数的写法(我也写个试试去)

class Solution(object):    def detectCapitalUse(self, word):        """        :type word: str        :rtype: bool        """        x = 0        for ch in word:            if 65<=ord(ch)<=96:                x = x+1        if len(word) == x or x == 0:            return True        if len(word) > 1 and x == 1 and 65<=ord(word[0])<=96:            return True        return False

不怎么使用辅助函数的方案

def detectCapitalUse(self, word):    total = 0    for c in word:        total += c.isupper()    return total == 0 or len(word) == total or (total == 1 and word[0].isupper())

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.

思路与解答

最开始我一直回避有关二叉树的题,算了,都是做,推平吧

不是单纯的左节点最深,右节点最深
那该怎么做呢
递归吧?好像不好写啊
即使找到两个最深的,如何确定分叉点呢,分叉点不同长度就不一样啊
如果找到最深的然后反作为起点。emmm,所以怎么确定最深的点呢。。。不对啊,知道最深的也走不回去啊
那只能一边遍历一边统计了

class Solution(object):    s=1    def diameterOfBinaryTree(self, root):        """        :type root: TreeNode        :rtype: int        """        def depth(roots):            if roots == None:return 0            rl = depth(roots.left)            rr = depth(roots.right)            self.s = max(self.s,rr+rl+1)            return max(rl,rr)+1        depth(root)        return self.s-1

答案

不使用那个算是全局变量的东西,利用l[0]来充当那个位置的方案

class Solution(object):    def diameterOfBinaryTree(self, root):        """        :type root: TreeNode        :rtype: int        """        def help(root): # return depth and diameter            if not root:                return [0,0]            left = help(root.left)            right = help(root.right)            return[max(left[0],right[0],left[1]+right[1]),1+max(left[1],right[1])]        return help(root)[0]

英雄所见略同

class Solution(object):    def diameterOfBinaryTree(self, root):        """        :type root: TreeNode        :rtype: int        """        self.ans = 0        def depth(p):            if not p: return 0            left = depth(p.left)            right = depth(p.right)            self.ans = max(self.ans, left + right)            return max(left, right) + 1        depth(root)        return self.ans

690. Employee Importance

题目

You are given a data structure of employee information, which includes the employee’s unique id, his importance value and his direct subordinates’ id.

For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, the relationship is not direct.

Now given the employee information of a company, and an employee id, you need to return the total importance value of this employee and all his subordinates.

Example 1:
Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
Output: 11
Explanation:
Employee 1 has importance value 5, and he has two direct subordinates: employee 2 and employee 3. They both have importance value 3. So the total importance value of employee 1 is 5 + 3 + 3 = 11.
Note:
One employee has at most one direct leader and may have several subordinates.
The maximum number of employees won’t exceed 2000.

思路与解答

这个题目就够长的了。。。
不太好懂,看起来还是遍历,深广都行吧,深度吧
emmmmm,所以我怎么找到id给的那个人?先遍历一下?那还是先广度吧
感觉我对题目的理解有问题QAQ
是的我sb了,我以为是一个树一样的东西,给一个大boss的地址,结果不是,提供的是员工列表
for循环里用return了,傻了

class Solution(object):    s=0    def getImportance(self, employees, id):        """        :type employees: Employee        :type id: int        :rtype: int        """                def findid(employees,id):            for emp in employees:                if emp.id == id:                    return emp        def sumemp(employees,emp):            self.s += emp.importance            if len(emp.subordinates) == 0:return            for sub in emp.subordinates:                  sumemp(employees,findid(employees,sub))          sumemp(employees,findid(employees,id))        return self.s

速度血崩,太慢了

答案

字典。嗯,我还是没有习惯用字典,根本没想过,那一个sum也很精髓,我为了不在for循环里使用return添加了一个全局变量

class Solution(object):    def getImportance(self, employees, id):        """        :type employees: Employee        :type id: int        :rtype: int        """        # Time: O(n)        # Space: O(n)        emps = {employee.id: employee for employee in employees}        def dfs(id):            subordinates_importance = sum([dfs(sub_id) for sub_id in emps[id].subordinates])            return subordinates_importance + emps[id].importance        return dfs(id)

这个比我的快一点

emps = {employee.id: employee for employee in employees}        dfs = lambda id: sum([dfs(sub_id) for sub_id in emps[id].subordinates]) + emps[id].importance        return dfs(id)

更快

        d={e.id:e for e in employees}        ret=0        stk=[d[id]] #we can go straight to the employee since we have a map already        while stk:             top=stk.pop()            ret+=top.importance            for n in top.subordinates:                stk.append(d[n])        return ret

找到一个一行的,但是运行出错了,估计是测试不完善时候提交的?
还有一些同样有些问题的。

172. Factorial Trailing Zeroes

题目

Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.

思路与解答

这道题差评率极高。。。
有时间复杂度的要求
所以题目是什么意思,大概是n!中从后往前数连续0的个数?
5的时候一个0,10时候2个?15,3个,20,4个,25,6个。。。好像明白了,可是怎么写出来呢

class Solution(object):    def trailingZeroes(self, n):        """        :type n: int        :rtype: int        """        c = 0        while n >= 5:            n /= 5            c +=  n        return c 

答案

一线版,巧妙的递归

    return 0 if n < 5 else n/5 + self.trailingZeroes(n/5)

……学会了and的一种用法

    return n and n/5 + self.trailingZeroes(n/5)

448. Find All Numbers Disappeared in an Array

题目

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]

思路与解答

看起来很简单,比如set,for循环,好像set都不需要,要不要用个字典,但没说n到底有多大

        l=[]        for n in range(1,len(nums)+1):            if n not in nums:                l.append(n)        return l 

第一版超时了咳咳

        d = {}        l = []        for n in nums:            d[n] = 1        for n in range(1,len(nums)+1):            if n not in d:                l.append(n)        return l 

字典版无所畏惧
考虑下怎么减少行数

        d = {}        for n in nums:            d[n] = 1        return [n for n in range(1,len(nums)+1) if n not in d]

列表生成式。。。好像不会再短了

答案

想哭,忘记取差集这种方案了

return list(set(range(1,len(nums)+1))-set(nums))

emmm并没有快,想法不错

        for i in xrange(len(nums)):            index = abs(nums[i]) - 1            nums[index] = - abs(nums[index])        return [i + 1 for i in range(len(nums)) if nums[i] > 0]
原创粉丝点击