https://leetcode.com/problems/search-insert-position/
https://leetcode.com/mockinterview/session/result/xjw45dt/
这是一个典型的二分查找。注意一些坑。比如里面start end的设置,到了边界条件时+1 -1的处理等。
package com.company; import java.util.*; class Solution { public int searchInsert(int[] nums, int target) { int start = 0; int end = nums.length - 1; int mid; while (start <= end) { mid = start + (end - start) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] > target) { end = mid - 1; } else { start = mid + 1; } } return start; } } public class Main { public static void main(String[] args) throws InterruptedException { System.out.println("Hello!"); Solution solution = new Solution(); // Your Codec object will be instantiated and called as such: int[] nums = {1,3,5,6,7}; int target = 7; int ret = solution.searchInsert(nums, target); System.out.printf("ret:%d ", ret); System.out.println(); } }