黄金分割图解
class FibonacciSelect
import java.util.Arrays;
public class FibonacciSelect {
public static void main(String[] args) {
int[] arrays={1,1,2,3,5,8,13,21,34,55,89};
System.out.println(select(arrays,13));
}
/**
* f[k]=f[k-1]+f[k-2]
* @return
*/
public static int[] f(){
int [] f=new int[20];
f[0]=1;
f[1]=1;
for(int i=2;i< f.length;i++){
f[i]=f[i-1]+f[i-2];
}
return f;
}
/**
* mid=low+F[k-1]-1;
* @param arrays
* @param key
* @return
*/
public static int select(int [] arrays,int key){
int low =0;
int hight= arrays.length;
int k=0;//k和求取中间值有关
int mid=0;
int [] f= f();
/**
* 找分割点
*/
while(hight>f[k]-1){
k++;
}
int[] temp= Arrays.copyOf(arrays,f[k]);
for(int i=hight+1;i<temp.length;i++){
temp[i]=arrays[hight-1];
}
while (low<=hight){
mid=low+f[k-1]-1;
if(key<temp[mid]){
hight=mid-1;
// f[k]=f[k-1]+f[k-2]
//要知道k是用来干什么的
k--;
}else if(key>temp[mid]){
low=mid+1;
//要知道k是用来干什么的
// f[k]=f[k-1]+f[k-2]
k-=2;
}else {
if(mid<=hight){
return mid;
}else {
return hight;
}
}
}
return -1;
}
}
你的点赞和关注,是我继续坚持下去的动力,如果可以请一键三连,谢谢!
个人知识水平有限,如果博客中有误,望指正。
如果欲交流学习,请私信我,我一定会在看到消息时及时回复你。