35 搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
示例 1:
输入: nums = [1,3,5,6], target = 5
输出: 2
示例 2:
输入: nums = [1,3,5,6], target = 2
输出: 1
示例 3:
输入: nums = [1,3,5,6], target = 7
输出: 4
提示:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums 为 无重复元素 的 升序 排列数组
-104 <= target <= 104
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/search-insert-position
解决方案:
提供思路
1) 普通方法:一个个比大小
2)二分法:因为数组已排序
上代码:
// 普通法
public class Solution {
public int SearchInsert(int[] nums, int target) {
for(int i = 0; i < nums.Length; i++)
{
if(nums[i] >= target) return i;
}
return nums.Length;
}
}
//二分法
public class Solution {
public int SearchInsert(int[] nums, int target)
{
int low = 0;
int high = nums.Length - 1;
int mid = 0;
while (low <= high)
{
mid = (low + high) / 2;
if (target == nums[mid]) return mid;
else if (target > nums[mid]) low = mid + 1;
else high = mid - 1;
}
//以上是常规的二分法
if (target > nums[mid]) return mid + 1;
else return mid;
}
}
以上是碰到的第三十五题,后续持续更新。感觉对你有帮助的小伙伴可以帮忙点个赞噢!