您的位置:首页 > 职场人生

面试题---数组中的元素相差为1,如何找到数t的位置

2017-05-20 22:31 302 查看
/**

* @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));

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法
相关文章推荐