We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
题目描述:
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 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
解题思路:题目比较简单,分情况,若比第一个数还小,返回0;若等于下标,返回下标;若遍历到了最后一个数,则返回最后一个数下标+1;若比当前数大,且小于其后一个数,返回当前下标+1
C++解题:
class Solution { public: int searchInsert(vector<int>& nums, int target) { if(nums[0] > target) return 0; for (int i = 0; i < nums.size(); i++) { if(nums[i] == target) return i; if(i == nums.size() - 1) return nums.size(); if(nums[i] < target && nums[i + 1] > target) return i+1; } return 0; } };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
题目描述:
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 1:
示例 2:
示例 3:
示例 4:
解题思路:题目比较简单,分情况,若比第一个数还小,返回0;若等于下标,返回下标;若遍历到了最后一个数,则返回最后一个数下标+1;若比当前数大,且小于其后一个数,返回当前下标+1
C++解题:
The text was updated successfully, but these errors were encountered: