LeetCode--Search Insert Position

Difficulty: Medium

【題目】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

翻譯

查找插入位置
難度系數(shù):中等
給定一個(gè)有序數(shù)組和一個(gè)目標(biāo)值,如果找到目標(biāo)值則返回該索引。如果不能,返回按照順序它應(yīng)被插入位置的索引。

一些示例

[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
// 二分檢索 時(shí)間復(fù)雜度log2(n)
- (int)searchInsertPosition:(NSArray<NSNumber *> *)sortedArray targetValue:(NSNumber *)target {
    
    if (sortedArray.count == 0) {
        
        return 0;
    }else {
        
        int left = 0;
        int right = (int)sortedArray.count - 1;
        
        while(left <= right) {
            
            int mid = (left+right)/2;
            
            if (sortedArray[mid] == target)
                
                return mid;
            else if (sortedArray[mid] > target)
                
                right = mid-1;
            else
                
                left = mid+1;
        }
        
        // left>right
        return left;
    }
}

之前學(xué)的C全就著饅頭進(jìn)肚子了。原諒我現(xiàn)階段只會用OC來寫,看起來不是很方便,最近在學(xué)Python,以后用Python寫吧

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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