Class Solution
Easy
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with O(log n)
runtime complexity.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:
Input: nums = [1,3,5,6], target = 7
Output: 4
Example 4:
Input: nums = [1,3,5,6], target = 0
Output: 0
Example 5:
Input: nums = [1], target = 0
Output: 0
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums
contains distinct values sorted in ascending order.-104 <= target <= 104
To solve the “Search Insert Position” problem in Java with a Solution
class, we can follow these steps:
- Define a
Solution
class. - Define a method named
searchInsert
that takes an integer arraynums
and an integertarget
as input and returns an integer representing the index wheretarget
would be inserted in order. - Implement binary search to find the insertion position of
target
. - Set the left pointer
left
to 0 and the right pointerright
to the length ofnums
minus 1. - While
left
is less than or equal toright
:- Calculate the middle index
mid
as(left + right) / 2
. - If
nums[mid]
is equal totarget
, returnmid
. - If
target
is less thannums[mid]
, updateright = mid - 1
. - If
target
is greater thannums[mid]
, updateleft = mid + 1
.
- Calculate the middle index
- If
target
is not found innums
, return the value ofleft
, which represents the index wheretarget
would be inserted in order.
Here’s the implementation:
public class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
} else if (target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return left;
}
}
This implementation provides a solution to the “Search Insert Position” problem in Java. It returns the index where target
would be inserted in nums
using binary search, with a time complexity of O(log n).
-
Constructor Summary
-
Method Summary
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
Constructor Details
-
Solution
public Solution()
-
-
Method Details
-
searchInsert
public int searchInsert(int[] nums, int target)
-