leetcode-35-search insert position

题目

现有一个已经排好序的数组,对于给定target,查找target在数组中插入的位置,保证数组依然是个升序排列

描述

举例说明:
[1,3,5,6] target = 5 ->2
[1,3,5,6] target = 2 ->1
[1,3,5,6] target = 7 ->4
[1,3,5,6] target = 0 ->0

Java代码实现

1
2
3
4
5
6
7
8
9
10
public class  {
public int searchInsert(int[] nums, int target) {

if(target < nums[0]) return 0;
int i = 0;
while(i < nums.length && nums[i] < target)
i++;
return i;
}
}