用空瓶子换汽水经常遇到 今天在论坛上有人提出来,给的算法用递归实现的 如果数量在百万那么时间复杂度我认为不合理
其实我认为这个问题很简单 如果几十个人需要喝汽水 完全可以根据数学模型口算出来 也就是说时间复杂度为n
数学模型:
N个瓶子换一瓶汽水。(假设瓶子的价钱为1)
瓶子价钱x 一瓶汽水除去瓶子本身的价钱实际价钱为y那么
N * x = x + y;
y = (N - 1 ) * x;
那么至少需要的money就很容易计算出来就可以计算出开始需要买几瓶汽水了
java代码如下:
package cn.xy.csdn;
public class Bottletosoda {
public static final int bottoleprice = 1;// 一个瓶子的价钱
private int percount = 3;// 每瓶汽水需要几个空瓶子换
private int sodacount = -1;// 需要的汽水的数量
public int sodaprice = 2;
public boolean flag = false;//是否允许使用最后的两个瓶子换一瓶汽水在将空瓶抵给卖方
public int getPercount() {
return percount;
}
public void setPercount(int percount) {
this.percount = percount;
}
public int getSodacount() {
return sodacount;
}
public void setSodacount(int sodacount) {
this.sodacount = sodacount;
}
public void compsodaprice() {
this.setSodaprice(bottoleprice * (this.getPercount() - 1));
}
public int getSodaprice() {
return sodaprice;
}
public void setSodaprice(int sodaprice) {
this.sodaprice = sodaprice;
}
public int buysodanumber() {
compsodaprice();
int needminmoney = this.getSodaprice() * this.getSodacount();
int lucysocle = needminmoney % (this.getSodaprice() + bottoleprice);
int minnumber = needminmoney
/ ((this.getSodaprice() + bottoleprice));
float realnum = (float) needminmoney / (float) (this.getSodaprice() + bottoleprice);
if ((!this.flag && lucysocle == 0) || realnum > (float)minnumber) {
minnumber += 1;
}
return minnumber;
}
public static void main(String[] s) {
Bottletosoda bt = new Bottletosoda();
bt.setSodacount(27);
System.out.println(bt.getSodacount() + "个人都喝到汽水至少应买的汽水瓶数为:"
+ bt.buysodanumber());
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}