#leetcode刷题之路35-搜索插入位置
生活随笔
收集整理的這篇文章主要介紹了
#leetcode刷题之路35-搜索插入位置
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個排序數組和一個目標值,在數組中找到目標值,并返回其索引。如果目標值不存在于數組中,返回它將會被按順序插入的位置。
你可以假設數組中無重復元素。
示例 1:
輸入: [1,3,5,6], 5
輸出: 2
示例 2:
輸入: [1,3,5,6], 2
輸出: 1
示例 3:
輸入: [1,3,5,6], 7
輸出: 4
示例 4:
輸入: [1,3,5,6], 0
輸出: 0
?
思路:二分法,找到目標值或者插入的位置。
#include <iostream> #include <vector> using namespace std;int searchInsert(vector<int>& nums, int target) {int low=0;int high=nums.size()-1;int mid;while (low<=high){mid=(low+high)/2;if(low==0&&0==high&&nums[low]<target) return low+1;if(low==0&&0==high&&nums[low]>target) return low;if(low==high&&nums[low]>target) return low;if(low==high&&nums[low]<target) return low+1;if(nums[mid]==target) return mid;else if(nums[mid]<target) low=mid+1;else high=mid-1;}return low; }int main() {int a=8;vector<int> aa={3,5,7,9,10};int ans=searchInsert(aa,a);std::cout << ans << std::endl;return 0; }?
轉載于:https://www.cnblogs.com/biat/p/10596878.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的#leetcode刷题之路35-搜索插入位置的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: git 中文乱码配置
- 下一篇: error LNK2038: 检测到“R