题目

35. 搜索插入位置

题解

代码

public class code35 {
    // public static int searchInsert(int[] nums, int target) {
    // for (int i = 0; i < nums.length; i++) {
    // if (nums[i] == target) {
    // return i;
    // }
    // }
    // int j = -1;
    // for (j = 0; j < nums.length; j++) {
    // if (nums[j] > target) {
    // return j;
    // }
    // }
    // return j;
    // }

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

    public static void main(String[] args) {
        int nums[] = { 1, 3, 5, 6 };
        int target1 = 5;
        int target2 = 2;
        int target3 = 7;
        int target4 = 0;
        int index1 = searchInsert(nums, target1);
        int index2 = searchInsert(nums, target2);
        int index3 = searchInsert(nums, target3);
        int index4 = searchInsert(nums, target4);
        System.out.println(index1);
        System.out.println(index2);
        System.out.println(index3);
        System.out.println(index4);
    }
}

参考

  1. 【特别推荐】十分好用的二分查找法模板(Python 代码、Java 代码)
  2. 画解算法:35. 搜索插入位置
  3. 特别好用的二分查找法模板(Python 代码、Java 代码)
  4. AcWing技术分享
  5. 二分查找算法模板