35. Search Insert Position

题目

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

题目的意思是,在数组中找到指定元素的index,如果找不到,那么返回它应该放置的正确index。

解答

我在SparseArray:解析与实现中刚好讲解了这个算法的应用。

其实就是一个二分查找算法,找不到就返回low的取反就可以了。但由于题目的意思不需要我们区分找到找不到这个情况,只需要告诉我index,那么就不需要取反了。

class Solution {
    public int searchInsert(int[] nums, int target) {
        int lo = 0;
        int hi = nums.length - 1;
        
        while (lo <= hi) {
            final int mid = (lo + hi) >>> 1;
            final int p = nums[mid];
            if (p > target) {
                hi = mid - 1;
            } else if (p < target) {
                lo = mid + 1;
            } else {
                return mid;
            }
        }
        
        return lo;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章