908. Smallest Range I

Given an array A of integers, for each integer A[i] we may choose any x with -K <= x <= K, and add x to A[i].

After this process, we have some array B.

Return the smallest possible difference between the maximum value of B and the minimum value of B.

说实话,看不懂题目在讲什么。一开始
给定一个数组A,对每个其中的数来说,我们可以从-k<x<k中选一个加到A中,那么我们就会得到一些数组B,然后返回数组B中最大值最小值相差最小的一个。

看了很久终于,明白了,这么简单的一个问题,被复杂成这样------

class Solution(object):
	def smallestRange1(self,A,K):
		return max(0,max(A)-min(A) -2k)

就是看最大值减去最小值看看多少,如果是正的就返回它,如果是负的就返回0。

再做一题:
881. Boats to Save People
The i-th person has weight people[i], and each boat can carry a maximum weight of limit.

Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit.

Return the minimum number of boats to carry every given person. (It is guaranteed each person can be carried by a boat.)

菜鸟上来当然是暴力解法啦
思路,先排序一下,如果最大和最小的不能坐同一个船,那么就只能让最大的自己坐一个船,如果可以那么弹出。

class Solution(object):
    def numRescueBoats(self, people, limit):
        """
        :type people: List[int]
        :type limit: int
        :rtype: int
        """
        people.sort()
        ans = 0
        while people:
            if people[-1] + people[0] >limit:
                people.pop()
                ans+=1
            else : 
                people.pop()
                people.pop(0)
                ans+=1
            if len(people) == 1:
                ans+=1
                people.pop()
        return ans

再看看大佬们的思路:
woqu,大佬思路和我一样,大喜过望,然后一看代码。。。大佬6行,我14行。妈也

class Solution(object):
    def numRescueBoats(self, people, limit):
        people.sort()
        i, j = 0, len(people) - 1
        ans = 0
        while i <= j:
            ans += 1
            if people[i] + people[j] <= limit:
                i += 1
            j -= 1
        return ans

思路不一样之处在于,我是面向people,大佬是面向指针。。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值