给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
输入: [1,3,5,6], 5
输出: 2
示例 2:
输入: [1,3,5,6], 2
输出: 1
示例 3:
输入: [1,3,5,6], 7
输出: 4
示例 4:
输入: [1,3,5,6], 0
输出: 0
本题主要采用的思路是基于集合和二分查找进行解决的,使用集合set的目的是为了去重,使用二分查找的目的是为了降低时间复杂度的,这就是本题的大致思路了。
import java.util.*;
import java.util.stream.Collectors;
/**
* @author pc
*/
public class SearchInsertTest {
public static void main(String[] args) {
int[] array = {1, 3, 5, 6};
int target = 0;
int searchInsert = searchInsert(array, target);
System.out.println("searchInsert = " + searchInsert);
}
public static int searchInsert(int[] nums, int target) {
Set<Integer> set = new LinkedHashSet<>(nums.length);
for (int num : nums) {
set.add(num);
}
set.add(target);
List<Integer> list = new ArrayList<>(set);
List<Integer> collect = list.stream().sorted(Integer::compareTo).collect(Collectors.toList());
int[] result = new int[collect.size()];
int i = 0;
for (int num : collect) {
result[i++] = num;
}
int left = 0;
int right = list.size() - 1;
while (left <= right) {
int mid = (right + left) / 2;
if (target == result[mid]) {
return mid;
} else if (target > result[mid]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
好久没有写类似的题了,好像距离上次更新时间已经过了大概一个月的时间了,这段时间为啥没有再写呢,一是自己有点迷茫,在反思自己为啥会迷茫?为啥会焦虑?如何解决迷茫呢?如何解决自己的焦虑呢?所以自己看了很多方法和解决方案。
就这样我慢慢梳理了自己很多不必要的想法,后面自己慢慢会把自己的想法分享一下的,到这里就结束了,如果喜欢我的文章,还请多分享,在此感谢。