LeetCode-35-Search Insert Position

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.

Here are few examples.

[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

Subscribe to see which companies asked this question.

翻譯(by google)

給定一個(gè)排序數(shù)組和一個(gè)目標(biāo)值,如果找到目標(biāo),則返回索引。如果沒有,返回索引的位置,如果它是按順序插入。

您可以假設(shè)數(shù)組中沒有重復(fù)項(xiàng)。

tag

  • Array 數(shù)組
  • Binary Search 二進(jìn)制搜索

解法

1.自己的 循環(huán)遍歷數(shù)組

public class Solution {
    public int SearchInsert(int[] nums, int target) {
        int i=0;
        for(i=0;i<nums.Length;i++) {
            if(nums[i] == target) return i;
            if(nums[i] > target) break;
        }
        return i;
    }
}

時(shí)間復(fù)雜度 O(n)


2.自己的 偏遞歸遍歷

public class Solution {
    public int SearchInsert(int[] nums, int target) {
        this.target = target;
        this.nums = nums;
        return Search(0);
    }
    public int target;
    public int[] nums;
    public int Search(int i) {
        if(i > nums.Length-1 ) return i;
        if(nums[i] >= target) return i;
        return Search(i + 1);
    }
}

遞歸的時(shí)間復(fù)雜度不好估,但是明顯比 單純想法 1 慢了


以下開始搜索網(wǎng)絡(luò)了

3.別人的 二分查找(http://blog.csdn.net/linhuanmars/article/details/20278967)

public class Solution {
    public int SearchInsert(int[] nums, int target) {  
    if(nums == null || nums.Length == 0)  
    {  
        return 0;  
    }  
    int l = 0;  
    int r = nums.Length-1;  
    while(l<=r)  
    {  
        int mid = (l+r)/2;  
        if(nums[mid]==target)  
            return mid;  
        if(nums[mid]<target)  
            l = mid+1;  
        else  
            r = mid-1;  
    }  
    return l;  
}
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容