35. 搜索插入位置

二分查找

class Solution {
    public int searchInsert(int[] nums, int target) {
        int ans = -1;
        int left = 0, right = nums.length;
        while (left < right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                ans = mid;
                break; // 注意break
            }
            else if (nums[mid] < target) left = mid + 1;
            else right = mid;
        }
        return ans < 0 ? left : ans;
    }
}

你可能感兴趣的:(LeetCode,算法,数据结构,java)