Finding the index of the closest element to a target in a sorted array using binary search in Java
I am trying to find the index of the element in a sorted integer array (nums) that is closest to a given target value. If there's a tie in difference, I want to handle it correctly. Here is the binary search approach I wrote: public class Solution { public static int binarySearchClosest(int[] nums, int left, int right, int target) { if (target <= nums[left]) return left; if (target >= nums[right]) return right; int low = left, high = right; int closestIndex = left; while (low <= high) { int mid = low + (high - low) / 2; if (nums[mid] == target) { return mid; } if (Math.abs(nums[mid] - target)
0 upvotes
View original discussion ↗
Comments
Sign in or sign up to comment and upvote.
No comments yet.