Guide: Binary Search is used to find target integer in a sorted array quickly. Binary search has left , right , and mid variables, but the target variable is what binary search is used for. Assume num2 is a sorted array in which we are searching for target. The Match: If nums2[mid] is exactly equal to your target, you've found a common number! You can immediately return it. Go Right: If your target is greater than nums2[mid], that means your target has to be in the right half of nums2. Move your left pointer to mid + 1. Go Left: If your target is smaller than nums2[mid], your target must be in the left half. Move your right pointer to mid - 1. //java int left = 0; int right = nums2.length - 1; int mid = 0; int target = 0; while(left <= right) { mid = left + (right - left) / 2; if(nums1[i] == nums2[mid]) { return target; } else { if(target < nums2[mid]) { right = mid - 1; } else { ...
coderEdge
Learn programming, data structures, and algorithms on CoderEdge with simple tutorials, coding examples, and guides for students and developers.