[LeetCode 35] Search Insert Position (easy)

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

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

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

Solution

  1. 根據二分法找target,如果找到則直接返回index
  2. 沒有找到,則需要根據start和end的值,來判斷index的值。
  3. 需要注意,example4中,如果target比index == 0的數還小時,此時返回的index就應該是0, 額入市start - 1.
class Solution {
    public int searchInsert(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        
        int start = 0;
        int end = nums.length - 1;
        
        while (start + 1 < end) {
            int middle = start + (end - start) / 2;
            
            if (target == nums [middle]) {
                return middle;
            }
            
            if (target > nums [middle]) {
                start = middle;
            } else {
                end = middle;
            }
        }
        
        if (target == nums [start])
            return start;
        if (target == nums [end])
            return end;
        
        // cannot find the target, then need to decide its order index
        if (target > nums [start] && target < nums [end]) {
            return start + 1;
        } else if (target > nums [end]) {
            return end + 1;
        } else if (target < nums [start]) {
            return start == 0 ? start : start - 1;
        }
        
        return -1;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容