• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

向小园

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

2020-2月3刷题

目录
  • 1、网易真题--牛牛找工作
    • 答案 py
    • 参考
      • python中sys.stdout、sys.stdin
      • python中的str.strip()的用法
      • python map() 函数
  • 其他
    • 添加leetcode70--爬楼梯的记忆化搜索/动规的cpp版本
    • 添加leetcode64--最小路径和动规的cpp版本
  • 动规--leetocde120--三角形最小路径和
    • 答案 cpp
  • 动规--leetocde343--整数拆分
    • 答案记忆化搜索 cpp
    • 答案DP cpp
    • 答案数学方法 cpp
  • 动规leetcode279--完全平方数
    • 答案DP cpp
    • 答案static DP 数学方法 待补充

1、网易真题--牛牛找工作

**动规、字典、快排**

答案 py

如下暴力会超时

import sys
def main():
    lines = sys.stdin.readlines()
    lines = [line.strip().split() for line in lines if line.strip()]
    N,M = int(lines[0][0]), int(lines[0][1])
    out=[0 for i in range(M)]
    for i in range(M):
        for j in range(1,N+1):
            if int(lines[N+1][i]) >= int(lines[j][0]): #能力值Ai >= 难度Dj
                if out[i] < int(lines[j][1]): #更新报酬Pi
                    out[i]=int(lines[j][1])
    for i in range(M):
        print(out[i])
if __name__=='__main__':
    main()

正确答案

import sys
def main():
    lines = sys.stdin.readlines()
    lines = [line.strip().split() for line in lines if line.strip()]
    N,M = int(lines[0][0]), int(lines[0][1])
    A=list(map(int,lines[-1]))
    maps=dict()
    res=[0]*(M+N)
    for i,line in enumerate(lines[1:-1]):
        d,p=int(line[0]),int(line[1])
        maps[d]=p 
        res[i]=d
    for i,a in enumerate(A):
        res[N+i]=a
        if a not in maps:
            maps[a]=0
    res.sort()
    MaxSalary=0
    for i in range(M+N):
        MaxSalary = max(MaxSalary,maps[res[i]])
        maps[res[i]] = MaxSalary
    for i in range(M):
        print(maps[A[i]])
if __name__=='__main__':
    main()

参考

python中sys.stdout、sys.stdin

如果需要更好的控制输出,而print不能满足需求,sys.stdout,sys.stdin,sys.stderr就是你需要的。

1. sys.stdout与print:

在python中调用print时,事实上调用了sys.stdout.write(obj+'\n')

print 将需要的内容打印到控制台,然后追加一个换行符

以下两行代码等价:

sys.stdout.write('hello' + '\n')
print('hello')

2. sys.stdin与input

sys.stdin.readline( )会将标准输入全部获取,包括末尾的'\n',因此用len计算长度时是把换行符'\n'算进去了的,但是input( )获取输入时返回的结果是不包含末尾的换行符'\n'的。

因此如果在平时使用sys.stdin.readline( )获取输入的话,不要忘了去掉末尾的换行符,可以用strip( )函数(sys.stdin.readline( ).strip('\n'))或sys.stdin.readline( )[:-1]这两种方法去掉换行。

3. 从控制台重定向到文件
原始的sys.stdout指向控制台,如果把文件的对象引用赋给sys.stdout,那么print调用的就是文件对象的write方法。

python中的str.strip()的用法

python中字符串str的strip()方法

str.strip()就是把字符串(str)的头和尾的空格,以及位于头尾的\n \t之类给删掉。

例1:

a= "\n ABC ABC ABC =========>KLJIFLJI \t \n"  
print(a)  
print(a.strip())

--->

![](https://images2018.cnblogs.com/blog/1220594/201803/1220594-20180322170919762-42128123.png)

补充:
字符串str还有另外两种类似的方法lstrip()和rstrip()。第一个是只删头,第二个是只删尾巴。

python map() 函数

map() 会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

map(function, iterable, ...)
* function -- 函数
* iterable -- 一个或多个序列
  • 返回值
    Python 2.x 返回列表。
    Python 3.x 返回迭代器。
  • 实例
>>>def square(x) :            # 计算平方数
...     return x ** 2
... 

#py3,返回迭代器,前面可加list转换
>>> map(square,[1,2,3,4,5])
<map object at 0x0000000002BBD6A0>
>>> list(map(square,[1,2,3,4,5]))
[1, 4, 9, 16, 25]

#py2,返回列表
>>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]

其他

添加leetcode70--爬楼梯的记忆化搜索/动规的cpp版本

添加leetcode64--最小路径和动规的cpp版本


动规--leetocde120--三角形最小路径和

自上而下的方法所需额外空间至少是和triangle同样大的空间,空间复杂度O(n*n),采用自下而上的动规方法只需要O(n)空间

答案 cpp

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        int m=triangle.size();
        vector<int> minmemo(triangle.back());
        for(int layer=m-2;layer>=0;layer--)
            for(int i=0;i<=layer;i++){
                minmemo[i]=min(minmemo[i],minmemo[i+1])+triangle[layer][i];
            }
        return minmemo[0];
    }
};

动规--leetocde343--整数拆分

答案记忆化搜索 cpp

记忆化搜索一定有一个memo列表,去除重复子结构

class Solution {
private:
    vector<int> memo;
    int breakInteger(int n){
        if(n==1)
            return 1;
        if(memo[n]!=-1)
            return memo[n];
        int res=-1;
        for(int i=1;i<=n-1;i++){
            res=max(res,max(i*breakInteger(n-i), i*(n-i)));
        }
        memo[n]=res;
        return res;
    }
public:
    int integerBreak(int n) {
        assert(n>=2);
        memo=vector<int>(n+1,-1);
        return breakInteger(n);
    }
};

答案DP cpp

//自底向上
class Solution {
public:
    int integerBreak(int n) {
        assert(n>=2);
        vector<int> memo(n+1,-1);
        memo[1]=1;
        memo[2]=1;
        for(int i=2;i<=n;i++)
            for(int j=1;j<=i-1;j++){
                memo[i]=max(memo[i],max(j*(i-j),j*memo[i-j]));
        }
        return memo[n];
    }
};

答案数学方法 cpp

来自于:推论3的n/3次方是最大值。

public int integerBreak(int n) {
			if (n < 3)
				return 1;
			if (n == 3)
				return 2;
			if (n % 3 == 0)
				return (int) Math.pow(3, n / 3);
			if (n % 3 == 1)
				return 2 * 2 * ((int) Math.pow(3, (n - 4) / 3));

			return 2 * ((int) Math.pow(3, (n - 2) / 3));
		}

动规leetcode279--完全平方数

答案DP cpp

class Solution {   
public:
    int numSquares(int n) {
        vector<int> cnt(n+1,INT_MAX);
        if(n<0)
            return 0;
        cnt[0]=0;
        for(int i=1;i<=n;i++)
            for(int j=1;j*j<=i;j++)
                cnt[i]=min(cnt[i],cnt[i-j*j]+1);
        return cnt[n];
    }
};

答案static DP 数学方法 待补充

posted on 2020-02-17 15:44  向小园  阅读(157)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3