一.要求
给定n个整数(地鼠)和一个整数(锤子),选出若干整数,从大到小排列后,任意相邻两数之差大于锤子,问最多能选出多少个数
二.解答
从两方向出发,一是项目层面,划模块便于阅读和修改,稳扎稳打;二是算法思维层面,尽量降低时间空间复杂度,科学取巧
项目层面:
思路:问题的本质是对无序list降序,逐次找出每个元素规定范围内的元素,组成新list,比较最大长度即可。
思维导图:
代码:
public void warOfMarmots(){
//初始化
List<Integer> marmots = new ArrayList();
Collections.addAll(marmots,65,23,89,77,23,65,21,36,923,0,35,5,36,54,312,36);
Integer hammer = 15;
List<Integer> newMarmots = new ArrayList<>();
//排序
for(int i = 0;i<marmots.size();i++){
if(newMarmots.size() == 0){ //list无数据可比时直接添加
newMarmots.add(marmots.get(i));
}else{
int tag = 0; //标记位,用于判断是否应加入list尾
for(int t = 0;t<newMarmots.size();t++){
if(marmots.get(i) > newMarmots.get(t)){
newMarmots.add(t,marmots.get(i));
break;
}
tag++;
}
if(tag == newMarmots.size()){
newMarmots.add(marmots.get(i));
}
}
}
//求每组鼹鼠数
List<Integer> numList = new ArrayList<>(); //装鼹鼠数
List<List<Integer>> testList = new ArrayList<>();
for(int i = 0;i<newMarmots.size();i++){
int num = 0;
Integer tempMarmots = newMarmots.get(i);
List<Integer> testList2 = new ArrayList<>();
for(int t=i;t<newMarmots.size();t++){
if(tempMarmots-newMarmots.get(t) > hammer){
tempMarmots = newMarmots.get(t);
testList2.add(tempMarmots);
num++;
}
}
testList.add(testList2);
numList.add(num);
}
//求最大鼹鼠数
int max = 0;
for(Integer num:numList){
if(max < num){
max = num;
}
}
System.out.println("the max is:"+max);
return;
}
三.杂谈:
- 偷得浮生半日闲,因时间有限,暂不做算法优化。
- 和女孩聊天时,她说的东西如果你听不懂,一定不要打断或仅仅表现听不懂,可以表现出努力去懂去好奇,认真听。
- 保持好奇