本文主要是介绍leetcode35-Search Insert Position,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
排序数组搜索某个元素,这种思维一定要往二分法上靠
public class searchInsertPosition{public static void main(String[] args) {int arr[] = {1,3,5,6};System.out.println(getIndex(arr,2));}public static int getIndex(int[] arr,int target) {int start = 0;int end = arr.length - 1;while(start <= end) {int mid = (start + end) / 2;if(arr[mid] == target) {return mid;}if(arr[mid] < target) {start = mid + 1;} else {end = mid - 1;}}return start;}
}
这篇关于leetcode35-Search Insert Position的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!