LeetCode 35. Search Insert Position

Borris發表於2020-02-06

LeetCode 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.

解法一 Binary Search

思路

要在有序陣列裡找到插入目標的位置,首先想到就是利用二分查詢,將 target 和陣列裡的數進行比較。

程式碼
class Solution {
    public int searchInsert(int[] nums, int target) {
        // Handle edge case
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int lo = 0;
        int hi = nums.length - 1;

        while (lo + 1 < hi) {
            int mid = (hi - lo) / 2 + lo;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target) {
                hi = mid;
            } else {
                lo = mid;
            }
        }

        // 由於退出迴圈時 相鄰的兩個 hi, lo 索引未與 target 進行比較,所以還要進行一次比較
        if (nums[hi] < target) {
            return hi + 1;
        } else if (nums[lo] >= target) {
            return lo;
        }
        return hi;
    }
}
複雜度分析
  • 時間複雜度
    • O(nlogn)
  • 空間複雜度
    • O(1)
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章