首页 > 试题广场 >

给定一个不下降的序列Sn{s1, s2... sn},以及一

[问答题]


给定一个不下降的序列Sn{s1, s2... sn},以及一个m,* * * * */

找到最小的k,使得s[k] = m,如果不存在输出-1 test case :S = {1,3,4} m = 3 , k = 2
S = {1,2,2,2,,2} m = 2, k = 2

public class Problem2 {
public static void main(String[] args) {
System.out.println(find(new int[]{1}, 2));//-1 
System.out.println(find(new int[]{2,3}, 2));//1 
System.out.println(find(new int[]{1,2}, 2));//2 
System.out.println(find(new int[]{1,3,4}, 3)); //2 
System.out.println(find(new int[]{1,2,2,2,2}, 2));//2 
System.out.println(find(new int[]{2,2,2,2,2}, 2));//1 
System.out.println(find(new int[]{1,1,3,3,4,5}, 2));//-1
} /** 



const find = (arr, target, left = 0, right = arr.length - 1) => {
    if (left > right) return -1
    const mid = Math.floor((left + right) / 2) //必须是向下取整,否则会死循环
    if (target === arr[mid]) {
        if (left === right) return mid 
        return find(arr, target, left, mid)
    }
    if (target < arr[mid]) return find(arr, target, left, mid - 1)
    return find(arr, target, mid + 1, right)
}

发表于 2019-09-16 16:24:24 回复(1)
直接求左边界
public int leftBorder(int[] S, int m) {
    if(S == null || S.length == 0) return -1;
    if(m < S[0] || m > S[S.length - 1]) return -1;
    int l = 0, r = S.length - 1;
    while(l <= r) {
        int mid = (r - l) / 2 + l;
        if(S[mid] >= m) 
            r = mid - 1;
        else
            l = mid + 1;
    }
    return S[l] == m ? l: -1;
}
发表于 2020-07-29 09:38:41 回复(0)
package DP;

public class MinIndex {
    
    public static int find(int a[], int b)
    {
        int result = -1; 
        int i = 0; 
        while(i < a.length && a[i] <= b)
        {
            if (a[i] == b)
            {
                result = i+1;
                break;
            }
            else 
                i++;
            
        }
        
        return result;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        System.out.println(find(new int[]{1}, 2));//-1 
        System.out.println(find(new int[]{2,3}, 2));//1 
        System.out.println(find(new int[]{1,2}, 2));//2 
        System.out.println(find(new int[]{1,3,4}, 3)); //2 
        System.out.println(find(new int[]{1,2,2,2,2}, 2));//2 
        System.out.println(find(new int[]{2,2,2,2,2}, 2));//1 
        System.out.println(find(new int[]{1,1,3,3,4,5}, 2));//-1

    }

}
 
发表于 2018-08-08 16:53:26 回复(0)

因为题目里说了是不下降的数组,所以一次二分查找就够了,外加一个初始化为-1的整数记录下标

发表于 2018-08-06 21:53:01 回复(0)