关于java:Java二分法总结

33次阅读

共计 1089 个字符,预计需要花费 3 分钟才能阅读完成。

一:用法

1、有序、无反复的数组
2、当有反复时,能够先用二分法查找到,而后应用左右滑动来找到边界
3、二分法例子:

  • 给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target,写一个函数搜寻 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
public class Search {public static void main(String[] args) {int[] nums = {-1, 0, 3, 5, 9, 12};
//        int target = 9;
        int target = 2;

        // 办法一:暴力循环
        int i = method1(nums, target);
        System.out.println(i);

        // 办法二:target【】双闭区间
        int get2 = method2(nums, target);
        System.out.println(get2);

        // 办法三:【)左闭右开区间
        int get3 = method3(nums, target);
        System.out.println(get3);
    }

    private static int method3(int[] nums, int target) {

        int left = 0;
        int right = nums.length;//[)
        while (left < right) {int mid = left + ((right - left) >> 1);
            if (nums[mid] > target) {right = mid;} else if (nums[mid] < target) {left =mid+1;} else if (nums[mid] == target) {return mid;}
        }
        return -1;


    }

    private static int method2(int[] nums, int target) {

        int left = 0;
        int right = nums.length - 1; // 因为此处是 -1,所以要用双闭区间
        while (left <= right) {int mid = left + ((right - left) >> 1);
            if (nums[mid] > target) {right = mid - 1;} else if (nums[mid] < target) {left = mid + 1;} else if (nums[mid] == target) {return mid;}
        }
        // 未找到指标
        return -1;

    }

    private static int method1(int[] nums, int target) {
        int get = -1;
        for (int i = 0; i < nums.length; i++) {if (nums[i] == target) {
                get = i;
                break;
            }
        }
        return get;
    }
}

二:区间

2.1:

正文完
 0