LeetCode-35. 搜索插入位置

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/love905661433/article/details/84061132

题目

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

你可以假设数组中无重复元素。

示例 1:

输入: [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

解题

  • 最简单的办法, 就是遍历一遍, 时间复杂度, 最优O(1), 最差O(n), 代码如下:
class Solution {
    public int searchInsert(int[] nums, int target) {
         for (int i = 0; i < nums.length; i++)
          if (nums[i] >= target)
              return i;
          return nums.length;
    }
    
}
  • 因为是有序数组, 所以可以使用二分搜索来处理, 在数据量较大的情况下, 二分搜索的效率更高, 时间复杂度是O(logn), LeetCode给的测试用例数据量都不大, 所以二分搜索的性能并不高于直接遍历的方法, 代码如下:
class Solution35 {
  public int searchInsert(int[] nums, int target) {
      int index = findIndex(nums, 0, nums.length - 1, target);
      return index;
  }
  
  
  private int findIndex(int[] nums, int left, int right, int target){
       if(target > nums[right]){
          return right + 1;
      }
      if(target < nums[left]){
          return left;
      }
      if(right == left){
          return right;
      }
      int mid = (right - left + 1) / 2 + left;
      if(target == nums[mid]){
          return mid;
      } else if (target > nums[mid]){
          return findIndex(nums, mid + 1, right, target);
      } else {
          return findIndex(nums, left, mid - 1, target);
      }
      
  }

猜你喜欢

转载自blog.csdn.net/love905661433/article/details/84061132