问题描述:给定一个有序序列,如果找到target,返回下标,如果找不到,返回插入位置。
算法分析:依旧利用二分查找算法。
1 public int searchInsert(int[] nums, int target) 2 { 3 return binarySearch(nums, 0, nums.length - 1, target); 4 } 5 public int binarySearch(int[] nums, int left, int right, int target) 6 { 7 int mid = (left + right)/2; 8 if(left > right) 9 { 10 return left; 11 } 12 if(nums[mid] == target) 13 { 14 return mid; 15 } 16 else if(nums[mid] < target) 17 { 18 return binarySearch(nums, mid + 1, right, target); 19 } 20 else 21 { 22 return binarySearch(nums, left, mid - 1, target); 23 } 24 }
时间: 2024-10-27 12:09:12