LeetCodeAnimation/0035-search-insert-position/Code/2.java

21 lines
510 B
Java
Raw Normal View History

2020-05-06 10:30:06 +08:00
//时间复杂度O(lon(n))
//空间复杂度O(1)
class Solution2 {
public int searchInsert(int[] nums, int target) {
if (target>nums[nums.length-1]) {
return nums.length;
}
int left=0;
int right=nums.length-1;
while (left < right) {
int mid = (left + right) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
}