LeetCode之搜索插入位置

it2023-11-05  77

题目: 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 你可以假设数组中无重复元素 示例:

方法一:

class Solution { public int searchInsert(int[] nums, int target) { int i=nums.length-1,index=-1; while(i>=0) { if(nums[i]>target){i--;continue;} if(nums[i]==target) { index=i; i--; while(i>=0&&target==nums[i]){ index=i--; } return index; }else if(nums[i]<target) { return i+1; }i--; } return 0; } }

方法二:二分查找

class Solution { public int searchInsert(int[] nums, int target) { int n = nums.length; int left = 0, right = n - 1, ans = n; while (left <= right) { int mid = ((right - left) >> 1) + left; if (target <= nums[mid]) { ans = mid; right = mid - 1; } else { left = mid + 1; } } return ans; } }
最新回复(0)