import java.util.Arrays;
import java.util.Scanner;
public class Demo3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int nums[] = new int[] { 1, 3, 5, 6 };// 假设数组中没有重复元素
System.out.println("请输入目标值");
int target = sc.nextInt();// 假设插入的是2 1 3 5 6 2
int index = searchInsert(nums, target);
System.out.println(index);
}
public static int searchInsert(int[] nums, int target) {
boolean flag = false;// 我们的目标值target
for (int i = 0; i < nums.length; i++) {
if (target == nums[i]) {
return i;
} else {
flag = true;
}
}
if (flag) {
nums = Arrays.copyOf(nums, nums.length + 1);
nums[nums.length - 1] = target;
Arrays.sort(nums);// 1 2 3 5 6
}
int j = 0;
for (; j < nums.length; j++) {
if (target == nums[j]) {
break;
}
}
return j;
}
}
第二种(二分查找法)
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (target == nums[mid]) {
return mid;
} else if (target > nums[mid]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left ;
}
}