题目描述:给定一个排序数组和一个目标值,如果找到目标,则返回索引。如果没有,返回索引的位置,如果它是按顺序插入。
题目样例:
[1,3,5,6],
5 → 2
[1,3,5,6],
2 → 1
[1,3,5,6],
7 → 4
[1,3,5,6],
0 → 0
算法设计如下:
public static int searchInsert(int[] nums, int target) {
int temp=0;
if(nums.length==0)
return 1;
if(nums.length==1)
{
temp=nums[0]>=target?0:1;
return temp;
}
if(nums[0]>=target)
{
temp=0;
}
for(int i=1;i<nums.length;i++)
{
if(nums[i]==target)
temp=i;
else if(nums[i-1]<target&&nums[i]>target)
temp=i;
else if(nums[i]<target&&i==nums.length-1)
temp=nums.length;
}
return temp;
}
本文介绍了一种用于在已排序数组中查找特定目标值或确定其插入位置的算法。通过遍历数组,该算法能够有效地定位目标值或计算出若要保持数组有序,目标值应插入的具体位置。
459

被折叠的 条评论
为什么被折叠?



