国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

35.LeetCode-- Array--Search Insert Position(在已排序數組內找元素(該元素可能存在或不存在))

2019-11-10 21:15:32
字體:
來源:轉載
供稿:網友
// 參考http://blog.csdn.net/u014221279/article/details/51546739class Solution {public:    int searchInsert(vector<int>& nums, int target)         {        // 邊界檢查        int n = nums.size();        if (n == 0) return -1;                // 二分法        // 包括了target < nums[0] 或 target > nums[n - 1]的情況        // 當 target == nums[mid]時,   直接找到了"原數";        // 當 最終nums[mid] < target時,說明"原數"不存在,會找到"比原數大一個的數"(此時low > high終止循環)        int low = 0;        int high = n - 1;               // 若nums的長度為 1 也ok。((n == 1) ? n : n - 1);        int mid;                while(low <= high)        {            mid = low + (high - low) / 2;            if(nums[mid] == target)                return mid;            else if(nums[mid] < target) // 在右半部分繼續找                low = mid + 1;            else                        // 在左半部分繼續找                high = mid - 1;         }        return low;                     // 因為找的是"原數"(若原數存在) 或 "比原數大一個的數"(若原數不存在),故返回low。    }};

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.

已排序的數組中如果有要插入的數組子,直接返回下標,即mid。

若沒有,則會一直查到到low》high  此時 返回low即可


上一篇:D. Mahmoud and a Dictionary

下一篇:memset

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 万全县| 清镇市| 大方县| 奉化市| 垣曲县| 仲巴县| 鄂温| 临江市| 恩平市| 天镇县| 芜湖县| 当雄县| 合作市| 遵义县| 绥滨县| 蓬莱市| 通河县| 鹤壁市| 中西区| 刚察县| 光泽县| 泾川县| 巩义市| 翁源县| 昌邑市| 濉溪县| 渝北区| 维西| 沧州市| 汉源县| 泾源县| 苗栗县| 三原县| 民丰县| 衡山县| 怀安县| 调兵山市| 竹北市| 科技| 朝阳县| 义乌市|