Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Given an array of integers nums which is sorted in ascending order,
- // and an integer target, write a function to search target in nums.
- // If target exists, then return its index. Otherwise, return -1.
- //
- //You must write an algorithm with O(log n) runtime complexity
- public class Solution {
- public int search(int[] nums, int target) {
- return binarySearch(nums, 0, nums.length, target);
- }
- public int binarySearch(int[] nums, int l, int r, int target) {
- if (l == r) {
- return -1;
- }
- if (r - l == 1) {
- if (nums[l] != target) {
- return -1;
- }
- return l;
- }
- int mid = (l + r) / 2;
- if (nums[mid] > target) {
- return binarySearch(nums, l, mid, target);
- }
- return binarySearch(nums, mid, r, target);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement