SearchInsertPosition-LeetCode

LeetCode38

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

離職後的第一題想先簡單點熱個身(後面有個難的目前還沒做出來),就是說給一個target,返回它在數組中的位置

How

該題目一上腦子就可以寫下如下的代碼

public int searchInsert(int[] nums, int target) {
    if (nums == null || nums.length == 0) {
        return 0;
    }
    if (target > nums[nums.length - 1]) {
        return nums.length;
    }
    int pos =1;
    for(int i =0;i<nums.length-1;i++){
         if(nums[i]<target && nums[i+1]>=target){
            pos = ++i;
            break;
        }
    }
    return  pos;
}

但轉念一想,題目中給定的是一個sorted array這是一個優化的切口,可以將O(n)的複雜度降低到O(logn),通過遞歸來拆解完成這道題

private int searchInsert(int[] nums, int target, int low, int high) {
        int mid = (low+high)/2;
        
        if (target < nums[mid]) {
            if (mid == 0 || target > nums[mid-1]) {
                return mid;
            }
            return searchInsert(nums, target, low, mid-1);
        }
        
        if (target > nums[mid]) {
            if (mid == nums.length-1 || target < nums[mid+1]) {
                return mid+1;
            }
            return searchInsert(nums, target, mid+1, high);
        }
        
        return mid;
    }
發佈了82 篇原創文章 · 獲贊 6 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章