题目:搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。你可以假设数组中无重复元素。复制代码
示例:
输入: [1,3,5,6], 5输出: 2输入: [1,3,5,6], 2输出: 1输入: [1,3,5,6], 7输出: 4输入: [1,3,5,6], 0输出: 0复制代码
思考:
因为数排序数组,所以循环数组元素找到与目标值相等或者第一个大于目标值的元素,返回其数组下标即可。复制代码
实现:
class Solution { public int searchInsert(int[] nums, int target) { for (int count = 0; count < nums.length; count++) { if (nums[count] == target||nums[count] > target) { return count; } } return nums.length; }}复制代码