python练习(十)

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

Maximum Product of Three Numbers

题目

Given an integer array, find three numbers whose product is maximum and output the maximum product.

Example 1:
Input: [1,2,3]
Output: 6
Example 2:
Input: [1,2,3,4]
Output: 24
Note:
The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
Multiplication of any three numbers in the input won’t exceed the range of 32-bit signed integer.

思路与解答

感觉非常简单,但是 怎么弄比较快呢
sorted,-1,-2,-3
测试:
Input:
[-4,-3,-2,-1,60]
Output:
120
Expected:
720
还带这样玩的?

反正3个数,最大那个数肯定是要的,只要比较前两个数相乘和倒数23的积即可
可以写一行,但是不好看

class Solution(object):
    def maximumProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        num = sorted(nums)
        return num[-1]*(num[-2]*num[-3] if num[-2]*num[-3] > num[0]*num[1] else num[0]*num[1])

42%应该没大问题

答案

class Solution(object):
    def maximumProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        return max( nums[-1]*nums[-2]*nums[-3], nums[-1]*nums[0]*nums[1] )

我好像又

class Solution(object):
    def maximumProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        max1,max2,max3,min1,min2=-1000,-1000,-1000,0,0
        for i in nums:
            if i>max3:
                if i<=max2:
                    max3=i
                else:
                    if i<=max1:
                        max3=max2
                        max2=i
                    else:
                        max3=max2
                        max2=max1
                        max1=i
            if i<min2:
                if i>=min1:
                    min2=i
                else:
                    min2=min1
                    min1=i
        if max2*max3<min1*min2:
            return max1*min1*min2
        else:
            return max1*max2*max3

这个代码比我的几乎快一倍(62:112)
大概是没有使用sorted的缘故?

一些小讨论

def maximumProduct(self, A):
    A.sort()
    if len(A) > 6:
        A = A[:3] + A[-3:]

    return max(A[i] * A[j] * A[k]
               for i in xrange(len(A))
               for j in xrange(i+1, len(A))
               for k in xrange(j+1, len(A)))

修改后

def maximumProduct(self, A):
    A.sort()
    del A[3:-3]
    return max(a * b * c for a, b, c in itertools.combinations(A, 3))

Maximum Average Subarray I

题目

Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.

Example 1:
Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
Note:
1 <= k <= n <= 30,000.
Elements of the given array will be in the range [-10,000, 10,000].

思路与解答

这不是最大子数组的和的变种嘛

class Solution(object):
    def findMaxAverage(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: float
        """
        smax = ss = 0
        for i,v in enumerate(nums):
            if i < k:
                ss += v
            else:
                ss += v
                ss -= nums[i-k]

            smax = max(smax,ss)

        return float(smax)/k

Input:
[-1]
1
Output:
0.00000
Expected:
-1.00000

忽略了只有一个元素的情况

又错了,但是输入太长了

是因为smax判断的位置不对,在最开始累加的时候就改变了smax(如果从第一个数以后越加越小的话),导致smax不对
然后发现smax不能初值为0啊,万一队列全是负数,smax=0就有问题了
后来修改了smax位置,但在测试时发现k==len(nums)的时候,出现异常,由于smax没有赋初值
想在for循环内部添加判断,但是i==k的判断不行,会出错,因为k==len(nums)时运行不到i==k的
然后打算把这个当特例处理,毕竟k==len(nums)很显眼嘛
所以smax的初值问题呢,经过思考

class Solution(object):
    def findMaxAverage(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: float
        """
        if len(nums) == 1:return float(nums[0])
        ss = 0
        for i,v in enumerate(nums):
            if i >= k:     
                ss += v
                ss -= nums[i-k]
                smax = max(smax,ss)
            elif i < k:
                ss += v
                if i == k-1: smax=ss
        return float(smax)/k

30%,但是150:290就很难用电脑问题来解释了

答案

class Solution(object):
    def findMaxAverage(self, nums, k):
        n = len(nums)
        assert(k >= 1 and k <= n and n <= 10000)

        s = sum(nums[0:k])
        ave = s * 1.0 / k

        for i in range(len(nums) - k):
            s = s - nums[i] + nums[i+k]
            ave = max(ave, s * 1.0 / k)

        return ave

还有个断言…
。。。好吧,这人提交的时候是150ms,我自己提交了3次大都是250ms…
不过他的确实比我的短啊

重写

class Solution(object):
    def findMaxAverage(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: float
        """
        smax = ss =sum(nums[:k])
        for i in range(k,len(nums)):    
            ss += nums[i] - nums[i-k]
            smax = max(smax,ss)
        return smax*1.0/k

这样就短了吧

听说你比较短

#使用前缀和(其中sums[i]是第一个i数字的总和)来计算子阵列和。

def findMaxAverage(self, nums, k):
    sums = [0] + list(itertools.accumulate(nums))
    return max(map(operator.sub, sums[k:], sums)) / k
#NumPy版本(需要import numpy as np):

def findMaxAverage(self, nums, k):
    sums = np.cumsum([0] + nums)
    return int(max(sums[k:] - sums[:-k])) / k

给大佬递茶 StefanPochmann
sub是相减
accumulate()也猜到是什么功能的函数了

accumulate()    p [,func]   p0,p0 + p1,p0 + p1 + p2,...

sums是从0开始的和,sums[k:]是从k开始的。相减即k个值的和,取最大值
np是矩阵语言,按元素逐个计算
很尴尬的事情,第一个不知道为什么不认accumulate函数,哪怕import itertools都不行
第二个把int改为float就可以了,270ms,很不错

Poor Pigs

题目

There are 1000 buckets, one and only one of them contains poison, the rest are filled with water. They all look the same. If a pig drinks that poison it will die within 15 minutes. What is the minimum amount of pigs you need to figure out which bucket contains the poison within one hour.

Answer this question, and write an algorithm for the follow-up general case.

Follow-up:

If there are n buckets and a pig drinking poison will die within m minutes, how many pigs (x) you need to figure out the “poison” bucket within p minutes? There is exact one bucket with poison.

思路与解答

这个问题的基础解答方案我都不知道啊
先想想基础版的吧,1000桶,15分钟,一小时内,也就是一头猪可以测4次,嗯,如果按二进制来算的话,10头猪一次就搞定了,可是如果分4次的话,万一是个巧妙的数字第一次就把猪都带走了怎么办。
怎么分4次呢,1000/4=250<256 即2的8次方,也就是8头猪?感觉不太对呢
上网搜了下
分四次的后果是 1000 < 3125 即5的5次方,那题目就比较明朗了

那个说一头猪,隔两秒喂一次的一边玩去!!!
唔,题目说的是15分钟内死亡。

答案

啊啊啊啊

class Solution(object):
    def poorPigs(self, buckets, minutesToDie, minutesToTest):
        """
        :type buckets: int
        :type minutesToDie: int
        :type minutesToTest: int
        :rtype: int
        """
        pigs = 0
        while (minutesToTest / minutesToDie + 1) ** pigs < buckets:
            pigs += 1
        return pigs

Number of 1 Bits

题目

Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.

思路与解答

。。。

    return bin(n).count('1')

嗯,过了
python真是过分(结果就是c++,java都是0ms,python是30ms)

答案

还能有什么呢

Nim Game

题目

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

思路与解答

这个怎么玩我知道的。只要不被4整除就行,即:

return n%4!=0

通过了。

答案

大同小异

有几道题有些水啊

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值