代码随想录算法训练营第35天|860.柠檬水找零 406.根据身高重建队列 452. 用最少数量的箭引爆气球

860.柠檬水找零 

代码随想录

class Solution(object):
    def lemonadeChange(self, bills):
        """
        :type bills: List[int]
        :rtype: bool
        """
        #five-bill
        five=0
        #ten-bill
        ten=0
        #count for loop
        count=0
        #loop when count < len(bills)
        while count < len(bills):
            # if bill=5,then five-bill increase one
            if bills[count]==5:
                five+=1
            #else if bill=10,we we will decrease one five-bill and increase
            #one ten-bill
            elif bills[count]==10:
                five-=1
                ten+=1
            #else if it is 20 dollor,check if we have 10-dollar first,
            #if yes, give ten-dollor first, if no, give five-dollar
            elif bills[count]==20:
                if ten:
                    ten-=1
                    five-=1
                else:
                    five-=3
            #each time check if we are run out of cash
            if five<0 or ten<0:
                return False
            count+=1
        # if there is no false return, which means true
        return True

406.根据身高重建队列 

代码随想录

class Solution(object):
    def reconstructQueue(self, people):
        """
        :type people: List[List[int]]
        :rtype: List[List[int]]
        """
        #sort by decreasing x[0]
        people.sort(key=lambda x: (-x[0], x[1]))
        que = []
        #now we can insert from the first index
        #when inserting, the index put in que should be the how many higher or 
        #the same height it need,this is correct because the height after 
        #inserting will always smaller, which will not affect previous index
        for p in people:
            que.insert(p[1], p)
        return que

452. 用最少数量的箭引爆气球 

代码随想录

class Solution(object):
    def findMinArrowShots(self, points):
        """
        :type points: List[List[int]]
        :rtype: int
        """
        #none
        if len(points) == 0: return 0
        #sort
        points.sort(key=lambda x:(x[0]))
        #1 because no matter what you need shoot an arrow
        arrow=1
        #loop start from index 1
        for i in range(1,len(points)):
            #if cur left boundary is bigger than pre right boundary
            #no overlap
            if points[i][0] > points[i - 1][1]:
                arrow+=1
                #else overlap 
            else:
                #renew the cur right boundary to smaller right boundary so that
                # arrow can still shoot the new balloon 
                points[i][1]=min(points[i - 1][1], points[i][1])
        return arrow

你可能感兴趣的:(算法,数据结构)