华为实习5.31(python)

题目

链接: link
第一次做算法笔试题,做完之后反思下

第一题(92%超时)

import heapq
def select_data(data , N):
    heap=[]
    for num in data:
        if len(heap) < N:
            heapq.heappush(heap, num)
        elif num >heap[0]:
            heapq.heapreplace(heap, num)
    heap.sort(reverse=True)

    result = ''.join(str(num) for num in heap)
    return result, heap

data = []
N, _ = map(int, input().split())

while True:
    try:
        a, b = map(int,input().split())
        data.append([b for _ in range(a)])
    except:
        break

heap=[]
for cur_batch in data:
    heap = heap + cur_batch
    res_data, heap = select_data(heap, N)
    print(res_data)

第二题

自己想的动态规划法

def my_minisum_squares(m, n):
    if m == n:
        return 1
    dp = [[0] * (n+1) for _ in range(m+1)]
    for i in range(1,m+1):
        for j in range(1, n+1):
            if i < j:
                dp[i][j] = 1 + dp[i][j - (j+1)//2]
            elif i > j:
                dp[i][j] = 1 + dp[i - (i+1)//2][j]
            else:
                dp[i][j] = 1
    print(dp)
    return dp[m][n]

def func():
    m= int(input())
    n = int(input())
    min_regions = my_minisum_squares(m, n)
    print(min_regions)

if __name__ == "__main__":
    func()

后来写的,只验证了示例,其他不知道对不对

第三题

没啥好说的,四个for循环,遍历四个变量:位置i,j和矩阵大小m,n,去计算cost,求最小cost

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值