/**
* @date 2017-05-20
* @author liuffei
* @description 数组里的元素相差1,如何找到数t的位置
*/
public class TLocation {
public static void main(String args[]){
//源数组
int[] source = {1,2,3,2,3,4,5,4,3,2,1,2,3};
System.out.println(findLoc(source,5));
}
}
* @date 2017-05-20
* @author liuffei
* @description 数组里的元素相差1,如何找到数t的位置
*/
public class TLocation {
//source表示某个数组,t表示要查找的数
public static int findLoc(int[] source,int t){
int n = source.length;
int pos = 0;//初始位置为0
//循环:如果当前位置上的数与查找的数t不一致,就计算两个数的差,进行跨越式遍历
while(pos < n){
pos += Math.abs(t-source[pos]);
if(t == source[pos]){
return pos;
}
}
return -1;//找不到返回-1
}
public static void main(String args[]){
//源数组
int[] source = {1,2,3,2,3,4,5,4,3,2,1,2,3};
System.out.println(findLoc(source,5));
}
}