取一个给定集合给定位置左右两侧等量集合的算法
前几天放到163上没人理,还是把这块砖扔出来吧!希望高人有更简洁的算法
163 链接:http://meiyitianabc.blog.163.com/blog/static/1050221272011113133756827/
文章正文
/**
* 21 size 算法
* @param maxSize 需要读取的最大数量
* @param list 集合
* @param current 当前所在位置
* @return 根据当前位置提取的集合
* @author meiyitian(zxy)
*/
public static ArrayList<Integer> getTwitterBy21(int maxSize,ArrayList<Integer> list ,int current){
int MAX = maxSize;
if(list==null||current<0||current>list.size()-1){
returnnull;
}
if(list.size()-1<=MAX){
return list;
}
ArrayList<Integer> tempList = new ArrayList<Integer>();
int temp = 0;
int offsetleft = 0;
int offsetright = 0;
int start =0;
int end =0;
int shouldDistance = (int) Math.round(MAX/2);
MAX = shouldDistance*2;
//search for offsetleft position .
temp = current;
for(int i=0;i<shouldDistance;i++){
temp = temp -1;
if(temp<=0){
offsetleft = i;
break;
}
offsetleft = i;
}
//search for offsetright position .
temp = current;
for(int i=0;i<shouldDistance;i++){
temp = temp+1;
if(temp>=list.size()){
offsetright = i;
break;
}
offsetright = i;
}
int distance = Math.abs(offsetright + offsetleft);
if((distance+1)<MAX){
System.out.println(""+"21:current ,(distance+1)<MAX");
if(offsetleft<shouldDistance-1){
end = current+offsetright + (MAX-distance);
if(end >list.size()-1){
end = list.size();
}
//start = current - offsetleft;
start = Math.round((MAX -2 -end )/2);
if(start<0){
start=0;
}
System.out.println(""+"21:current ,offsetleft<shouldDistance");
}else if(offsetright<shouldDistance-1){
start = current - offsetleft -(MAX-distance)+1;
if(start<0){
start =0;
}
//end = current + offsetright-1;
end = MAX-2+2*start;
if(end>list.size()){
end = list.size();
}
System.out.println(""+"21:current ,offsetright<shouldDistance");
}else if(offsetright ==offsetleft){
start = current - offsetleft-1;
if(start<0){
start = 0;
}
end = current+offsetright+1;
if(end>list.size()){
end = list.size();
}
}
}
//add ...
for(int i = start ;i<end;i++){
tempList.add(list.get(i));
}
System.out.println(""+"21:size ,"+tempList.size());
return tempList;
}