Loading... <span class="label bg-success">简单</span> ## 题目 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 你可以假设数组中无重复元素。 示例 1: ```text 输入: [1,3,5,6], 5 输出: 2 ``` 示例 2: ```text 输入: [1,3,5,6], 2 输出: 1 ``` 示例 3: ```text 输入: [1,3,5,6], 7 输出: 4 ``` 示例 4: ```text 输入: [1,3,5,6], 0 输出: 0 ``` ## 思路 二分查找 ## 代码 ```C++ int binarySearch(vector<int> nums, int left, int right, int target) { if (target < nums[left]) return left; if (target > nums[right]) return right + 1; if (left >= right) { if (target <= nums[left]) { return left; } else { return left + 1; } } int middle = left + (right - left) / 2; if (target == nums[middle])return middle; else if (target < nums[middle]) { return binarySearch(nums, left, middle, target); } else { return binarySearch(nums, middle + 1, right, target); } } int searchInsert(vector<int> &nums, int target) { return binarySearch(nums, 0, nums.size() - 1, target); } ``` ![leetcode-cn35.png][1] [1]: http://alomerry.com/usr/uploads/2020/08/2951177734.png<hr class="content-copyright" style="margin-top:50px" /><blockquote class="content-copyright" style="font-style:normal"><p class="content-copyright">版权属于:清欢</p><p class="content-copyright">本文链接:<a class="content-copyright" href="http://alomerry.com/archives/411/">http://alomerry.com/archives/411/</a></p><p class="content-copyright">转载时须注明出处及本声明</p></blockquote> Last modification:August 18th, 2020 at 07:11 pm © 允许规范转载 Support 觉得我的文章有帮助吗,欢迎赞赏呀(๑• . •๑) ×Close Appreciate the author Sweeping payments Pay by AliPay Pay by WeChat