Given a sorted array of distinct integers 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 must write an algorithm with O(log n) runtime complexity.
输入 | 输出 |
---|---|
nums = [1,3,5,6], target = 5 | 2 |
nums = [1,3,5,6], target = 2 | 1 |
nums = [1,3,5,6], target = 7 | 4 |
nums = [1,3,5,6], target = 0 | 0 |
nums = [1], target = 0 | 0 |
IDE:VS2019
IDE版本:16.10.1
语言:c++11
#include "Solution.h" #include <vector> // std::vector #include<iostream> // std::cout using namespace std; // 主程序 void main() { // // 输入 vector<int> nums = { 1,3,5,6 }; int val = 4; Solution solution; // 实例化Solution int k = solution.searchInsert(nums, val); // 主功能 // 输出 cout << k << endl; }
#pragma once #include<vector> // std::vector using namespace std; //主功能(二分法+递归) class Solution { public: int searchInsert(vector<int>& nums, int target) { int low = 0, high = nums.size()-1; while(low<=high) { int mid = low + (high - low)/2; if(target == nums[mid]) return mid; else if(target>nums[mid]) low = mid+1; else high = mid-1; } return low; } };
此程序参考:https://blog.csdn.net/lym940928/article/details/79893316
使用的是二分查找法,当while循环完成时,说明没有找到对应的数字,此时low > high,即low = high+1。因为数字树位于[low, hight+1]中的,也即位于[low,low]之中,因此返回low,即为target的最后的位置。
#pragma once #include<vector> // std::vector using namespace std; //主功能(二分法+递归) class Solution { public: int searchInsert(vector<int>& nums, int target) { if (target <= nums[0]) return 0; // 如果目标值比数组第一个元素还小,则返回0 else return func(nums, target, 0, nums.size()); // 运行主要函数 } int func(vector<int>& nums, int target, int left, int right) { int min = 0; if (right - left <= 1) return right; else { int mid = (left + right) / 2; if (nums[mid] > target) { right = mid; return func(nums, target, left, right); // 递归 } else if (nums[mid] < target) { left = mid; return func(nums, target, left, right); } else return mid; } } };
由约束条件一可知数组不为空数组,由约束条件三知数组里的元素是按照升序排列的,也就是说不用考虑降序排列的情况。另外由题目中要求时间复杂度为O(log n),可以联想到是用二分法进行求解,二分法的过程中还用到了递归的思想。
这个错误在VS2019中没有报,但是在Leetcode那里却报错了,当时挺蒙蔽的,后来查找资料才知道,原来是自己我if...else if...else if...else...里前几个没有return,也就是说有些情况没有返回值,考虑不周全。
这个可以参考:https://blog.csdn.net/pikaqiu123321123/article/details/114580378