DSA Problem Solution: Binary Search
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.
Example 1:
Input: nums = [-6,1,3,5,9,11], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
Input: nums = [-2,0,3,6,9,20], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
public class Solution { public int Search(int[] nums, int target) { return binarySearch(0,nums.Length-1, nums,target); } public int binarySearch(int startIndex, int lastIndex,int[] nums, int target) { if(startIndex>=lastIndex) { return nums[startIndex]==target?startIndex:-1; } int mid = (startIndex+lastIndex)/2; if(nums[mid]==target) { return mid; } else if(nums[mid]>target) { return binarySearch(startIndex,mid-1, nums,target); } else { return binarySearch(mid+1,lastIndex,nums,target); } } }
0 comments :
Post a Comment