package com.LeetCode;
/**
* 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
* <p>
* 你可以假设数组中无重复元素。
*/
public class SearchInsert {
public static void main(String[] args) {
int[] arr = {1, 3, 4, 6, 7};
int target = 9;
int i = searchInsert(arr, target);
System.out.println(i);
/*//采用二分查找法
int left = 0;
int right = arr.length - 1;
while (left < right) {
int mid = (right + left) / 2;
if (arr[mid] == target) {
System.out.println(mid);
} else if (arr[mid] > target) {
right = mid;
} else {
left = mid + 1;
}
}
//此时left = right,采用三元运算符
System.out.println(target <= arr[left] ? left : left + 1);*/
}
public static int searchInsert(int[] arr,int target){
//采用二分查找法
int left = 0;
int right = arr.length - 1;
while (left < right) {
int mid = (right + left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] > target) {
right = mid;
} else {
left = mid + 1;
}
}
//此时left = right,采用三元运算符
return target <= arr[left] ? left : left + 1;
}
}