在给定的有序数组中插入一个目标数字,求出插入该数字的下标
由于该数组是已经排好序的数组,可以利用二分查找。
 
二分查找的返回结果:
  1. 当查找的数字在数组中时,返回第一次出现的下标
      2. 当查找的数字不存在时,返回 - pos - 1(即 应当插入位置的相反数再减去 
 
 
参考代码: 
package leetcode_50;

import java.util.Arrays;

/***
 * 
 * @author pengfei_zheng
 * 找出插入元素应当插入的下标
 */
public class Solution35 {
    public static int searchInsert(int[] nums, int target) {
        int ans = Arrays.binarySearch(nums, target);
        if(ans>=0)
            return ans;
        else 
            return -ans-1;
    }
    public static void main(String[]args){
        int []nums={1,3,5,6};
        System.out.println(searchInsert(nums,0));
    }
    
}

 

 

相关文章:

  • 2021-08-09
  • 2021-07-12
  • 2021-09-27
  • 2021-09-07
  • 2021-09-21
  • 2021-09-29
  • 2021-11-08
  • 2022-03-06
猜你喜欢
  • 2022-01-30
  • 2021-09-20
  • 2022-01-08
  • 2021-10-15
  • 2022-01-03
  • 2021-07-12
  • 2021-08-12
相关资源
相似解决方案