求一个有序数组值为k的位置

求一个有序数组值为k的位置,如果包含多个,分别输出对应的位置,要求最差时间也是logN

代码如下

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**

  • Description: 二分查找

**/
public class BinarySearch {
public static int searchIndex(int key, Integer[] arr) {
if (arr == null || arr.length == 0) {
return -1;
}
int start = 0;
int end = arr.length - 1;
if (arr[start] > key || arr[end] < key) {
return -1;
}

    int mid = 0;
    while (start <= end) {
        mid = (start + end) / 2;
        if (arr[mid] > key) {
            end = mid - 1;
        } else if (arr[mid] < key) {
            start = mid + 1;
        } else {
            while (mid - 1 >= 0 && arr[mid - 1] == key) {
                mid--;
            }
            return mid;
        }
    }
    return -1;
}

public static Integer[] searchAllIndex(int key, Integer[] arr) {
    Integer[] result;
    if (arr == null || arr.length == 0) {
        return new Integer[0];
    }
    int start = 0;
    int end = arr.length - 1;
    if (arr[start] > key || arr[end] < key) {
        return new Integer[0];
    }

    int mid;
    while (start <= end) {
        mid = (start + end) / 2;
        if (arr[mid] > key) {
            end = mid - 1;
        } else if (arr[mid] < key) {
            start = mid + 1;
        } else {
            int midL = mid;
            int midR = mid;
            int count = 1;

            while (midL - 1 >= 0 && arr[midL - 1] == key) {
                count++;
                midL--;
            }
            while (midR + 1 < arr.length && arr[midR + 1] == key) {
                count++;
                midR++;
            }
            result = new Integer[count];
            for (int i = 0, from = midL; i < count; i++, from++) {
                result[i] = from;
            }
            return result;
        }
    }
    return new Integer[0];
}

}

猜你喜欢

转载自blog.csdn.net/godloveleo9527/article/details/109261959
今日推荐