python练习(七)

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

Construct the Rectangle

题目

For a web developer, it is very important to know how to design a web page’s size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:

  1. The area of the rectangular web page you designed must equal to the given target area.

  2. The width W should not be larger than the length L, which means L >= W.

  3. The difference between length L and width W should be as small as possible.
    You need to output the length L and the width W of the web page you designed in sequence.

思路

虽然题目看起来很厉害,但是感觉做起来不难(直接取平方根进行相应计算)

解答

class Solution(object):
    def constructRectangle(self, area):
        """
        :type area: int
        :rtype: List[int]
        """
        n = int(area**0.5)
        while area%n !=0:
            n -=1
        return [area/n,n]

答案

没有更好的了

Container With Most Water

题目

Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

思路

本来以为能生成一个倒三角的,心想不愧是中级难度的,仔细再读一遍,哦,看错了
没什么难度嘛(应该吧)
卧槽不能确定之前记录哪面墙啊
都乘一遍蠢死了,记一个远中最高的,再记个高中最远的?。。。好像没有远中最高的啊
给定一面墙,肯定是离他最远至少等高,哦?也不一定啊QAQ

解答

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        smax = 0
        kmax = 0
        vmax = 0
        for k,v in enumerate(height):
            if v < vmax:continue
            else:
                vmax = v
            kmax = 0
            for k2 in range(k+1,len(height))[::-1]:
                if height[k2] <= kmax : continue
                else:
                    kmax = height[k2]
                if min(v,height[k2])*(k2-k) > smax:
                    smax = min(v,height[k2])*abs(k2-k)
        return smax

二重循环超时

答案

感谢
虽然看起来很有道理,但是怎么实现呢

绘制一个矩阵,其中行是第一行,列是第二行。例如,假设n=6。

在下图中,x意味着我们不需要计算出这种情况的音量:(1)在对角线上,两条线重叠; (2)矩阵的左下角三角形区域与右上方区域对称。

我们从计算出的音量开始,由… (1,6)表示o。现在如果左边的行比右边的那条线短,那么(1,6)在第一行左边的所有元素的体积都比较小,所以我们不需要计算这些情况—。

  1 2 3 4 5 6
1 x ------- o
2 x x
3 x x x 
4 x x x x
5 x x x x x
6 x x x x x x

接下来我们移动左边的行并计算(2,6)。现在,如果正确的路线更短,以下所有情况(2,6)都将被删除。

  1 2 3 4 5 6
1 x ------- o
2 x x       o
3 x x x     |
4 x x x x   |
5 x x x x x |
6 x x x x x x

无论这个o路径如何,我们最终只需要在这个路径上找到包含大小写的最大值n-1。

  1 2 3 4 5 6
1 x ------- o
2 x x - o o o
3 x x x o | |
4 x x x x | |
5 x x x x x |
6 x x x x x x
class Solution:
    def maxArea(self, height):
        i, j = 0, len(height) - 1
        water = 0
        while i < j:
            water = max(water, (j - i) * min(height[i], height[j]))
            if height[i] < height[j]:
                i += 1
            else:
                j -= 1
        return water

从两边逼近,哦,原来是我之前想错了
不过,和上边的解释真的是一伙的吗

Contains Duplicate

题目

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

思路

果然划分为easy是有道理的
(题目阅读是hard的!!!最初以为判断没有重复,有重复False,没有True。心想代码肯定没错,难道读错题了?再读一遍,好像是判断所有元素是不是重复的,都是重复的返回True,有不是的返回False,测试的时候还是不对)
最后,仔仔细细的阅读了一遍题目,题目要求是:
判断是否没有重复,有重复True,没有False

解答

return True if len(nums) == len(set(nums)) else False

还想一行做的,看错题了,擦
那用Counter应该不错

from collections import Counter
class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if len(nums) == 0 :return False
        for i in Counter(nums).values():
            if i == 1:
                return False
        return True

好像不太对。。。我又读错题了?

return False if len(nums) == len(set(nums)) else True

呃。。。把第一次的代码反过来就好了,石乐志

答案

return len(nums) != len(set(nums))

原来这一行还能更简单,呃呃呃呃

First Unique Character in a String

题目

Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.

Examples:

s = “leetcode”
return 0.

s = “loveleetcode”,
return 2.

思路

Counter?

解答

from collections import Counter
class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        ss = Counter(s)
        for k,v in enumerate(s):
            if ss[v] == 1:return k
        return -1

300+ms
看起来别人有100-ms左右的方法啊

答案

    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """

        letters='abcdefghijklmnopqrstuvwxyz'
        index=[s.index(l) for l in letters if s.count(l) == 1]
        return min(index) if len(index) > 0 else -1

嗯…

class Solution(object):
    def firstUniqChar(self, s):
        return min([s.find(c) for c in string.ascii_lowercase if s.count(c)==1] or [-1])

嗯…比上边的那个慢了一点,可能是运行问题,因为感觉是一个意思
这个答主也说了使用Counter会比较慢…为啥呢

First Bad Version

题目

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, …, n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

思路

和猜数字的那个差不多?

解答

class Solution(object):
    def firstBadVersion(self, n):
        """
        :type n: int
        :rtype: int
        """
        l, r = 1, n
        if isBadVersion(1):return 1
        while l + 1 < r:
            m =  (r + l) / 2
            if isBadVersion(m):
                r = m
            else:
                l = m
        return r

确实有点像
99.70%

答案

#In Python I was only able to do it with a rather ugly wrapper:

def firstBadVersion(self, n):
    return bisect.bisect(type('', (), {'__getitem__': lambda self, i: isBadVersion(i)})(), False, 0, n)
#Nicer, more readable version:

def firstBadVersion(self, n):
    class Wrap:
        def __getitem__(self, i):
            return isBadVersion(i)
    return bisect.bisect(Wrap(), False, 0, n)

bisect.bisect(i)函数是在已排序列表中,返回i的插入位置,但并不会插入进去,真的只是蹭蹭
其兄弟函数bisect_leftbisect_right 分别返回左插位和右插位
和真的插进去的 insort_leftinsort_right

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值