Leetcode 35. Search Insert Position

本文详细解析了LeetCode上的一道经典题目——搜索插入位置。针对已排序的数组和目标值,提供了两种解决方案:一种是遍历查找,另一种是更高效的二分法查找。文章还附带了完整的代码实现。

Given a sorted array 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 may assume no duplicates in the array.

Here are few examples.

[1,3,5,6], 5 → 2

[1,3,5,6], 2 → 1

[1,3,5,6], 7 → 4

[1,3,5,6], 0 → 0

我的思路:

有序数组

首先考虑特殊情况,如果数组为空,那么输出的结果就一定为0;

当数组不为空时,对数组中的每个元素依次遍历,

当nums[i]等于target时,直接输出i,这便是target的索引;

当nums[i]小于target时,表示target可能还在后面,所以i增加1;直到i等于nums数组的长度,停止遍历,返回数组长度,及target应插入的位置。

当nums[i]大于target时,表示target不在数组中,同时target应该插入的位置为nums[i]前面的位置,因为前面遍历的nums[i-1]及前面的数都是小于target的,而此时的nums[i]又大于target。所以不再需要继续往后遍历,直接返回索引i,target应插入的位置。

class Solution {

public int searchInsert(int[] nums, int target) {

if(nums.length == 0){

return 0;

}

int i;

for(i = 0;i<nums.length;i++){

if(nums[i]==target){

return i;

}

else if(nums[i]>target){

return i;

}

}

return i;

}

}

leetcode上的solution:

leetcode上有个solution给出了二分法的解决办法。

首先两个记录边界的指针,low,和high(nums.length-1),还有中间值的指针,mid=(low+high)/2

class Solution {

public int searchInsert(int[] nums, int target) {

int low = 0;int high = nums.length-1;

for(low<high){

int mid = (low + high)/2;

if(nums[mid] == traget) return mid;

else if(nums[mid]>target){

high = mid-1;

}

else low = mid+1;

}

//return mid;

return low;

}

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值