1.货币问题
题解:
package offer.tencent;
import java.util.Scanner;
public class money {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
long m=sc.nextLong();
int sum=0;
//最简方法
System.out.println((m+n-1)/n);
for(int i=n;i>0;i--){
sum+=(int)(m/i);//需要的最大的货币数量
m%=i;//还需支付多少货币
i=(int)(m+1);//将i赋值为剩余价格的货币
if(m==0){//货币足够跳出循环
break;
}
}
System.out.println(sum);
}
}
2.奇妙的数列
题解:
package offer.tencent;
import java.util.Scanner;
public class sequence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int q = sc.nextInt();
for (int i = 0; i < q; i++) {
long l = sc.nextLong();
long r = sc.nextLong();
System.out.println((int)(Math.pow(-1,r)*((r+1)/2)-Math.pow(-1,l-1)*(l/2)));
//前r项和减去前l-1项和
if (l % 2 == 0) {
if ((r - l + 1) % 2 == 0) {//偶数开始,偶数个数
System.out.println(-(r - l + 1) / 2);
} else {
System.out.println((l + r) / 2);
}
} else {
if ((r - l + 1) % 2 == 0) {//奇数开始,偶数个数
System.out.println((r - l + 1) / 2);
} else {
System.out.println(-(l + r) / 2);
}
}
}
}
}
4.气球问题
题解:
#include<bits/stdc++.h>
using namespace std;
unordered_map<int, int> mp;
int main()
{
int n, m;
cin >> n >> m;
int satisfy = 0;
deque<int> q;
int res = INT_MAX;
for(int i = 1,x; i <= n; ++i)
{
cin >> x;
q.push_back(x);
if(!mp[x])satisfy ++;
mp[x]++;
if(satisfy == m)
{
if(q.size()) {
while(mp[q.front()] > 1)
mp[q.front()]--, q.pop_front();
int u = q.size();
res = min(res,u);
}
}
}
if(res == INT_MAX) res = -1;
cout << res << endl;
return 0;
}