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] <= 104numscontains 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
Solutionclass. - Define a method named
searchInsertthat takes an integer arraynumsand an integertargetas input and returns an integer representing the index wheretargetwould be inserted in order. - Implement binary search to find the insertion position of
target. - Set the left pointer
leftto 0 and the right pointerrightto the length ofnumsminus 1. - While
leftis less than or equal toright:- Calculate the middle index
midas(left + right) / 2. - If
nums[mid]is equal totarget, returnmid. - If
targetis less thannums[mid], updateright = mid - 1. - If
targetis greater thannums[mid], updateleft = mid + 1.
- Calculate the middle index
- If
targetis not found innums, return the value ofleft, which represents the index wheretargetwould 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
Constructors -
Method Summary
-
Constructor Details
-
Solution
public Solution()
-
-
Method Details
-
searchInsert
public int searchInsert(int[] nums, int target)
-