3.16 第35题 搜索插入位置
题目
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
解答
思路:列表本身的元素有排序过的 逐一遍历列表里面的元素 与目标值比较 最后如果没有列表元素没有大于目标值的 说明目标值最大 排在列表最后。、
import com.sun.xml.internal.xsom.XSTerm;
//小心数组越界问题
public class Solution35 {
public static int searchInsert(int[] nums,int target){
int i = 0;
while(nums[i] < target){
i++;
if(i == nums.length){
break;
}
}//while
return i;
}
public static void main(String[] args){
int[] nums = {1,2,3,5};
int target = 6;
int search = searchInsert(nums,target);
System.out.println(search);
}
}
别人的解答:
public static int searchInsert(int[] nums,int target){
int i = 0;
for(;i<nums.length;i++){
if(nums[i] >= target)
return i;
}
return i+1;//
}
知识点或坑
-
我使用while循环的时候,没有考虑数组越界问题,如果i遍历到数组最后,while循环判断语句还是会判断一次,这时,数组元素越界了,报java.lang.ArrayIndexOutOfBoundsException.
-
别人使用for循环,没有数组越界问题
for(;i<nums.length;i++)
注意:range(X)的取值范围是 0 ~ X-1 ,取不到X。