题解 | #牛群的位置排序#
牛群的位置排序
https://www.nowcoder.com/practice/87c81fa27b9a45c49ed56650dfa6f51b?tpId=354&tqId=10594812&ru=/exam/company&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Fcompany
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param labels int整型一维数组 * @param target int整型 * @return int整型 */ public int searchInsert (int[] labels, int target) { // write code here int left = 0, right = labels.length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (labels[mid] == target) { return mid; } else if (labels[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return left; } }
知识点:
分治
二分
解题思路:
给定一个有序数组 labels 和一个目标标签值 target,我们可以在数组中寻找该标签值的插入位置。如果数组中已经存在该标签值,那么插入位置就是它在数组中的索引;否则,插入位置就是数组中第一个大于目标标签值的元素的索引。