You are given an integer array
Suppose that
If
nums
sorted in ascending order (with distinct values), and an integer target
.Suppose that
nums
is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7]
might become [4,5,6,7,0,1,2]
).If
target
is found in the array return its index, otherwise, return -1
.Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Approach
Java
public class SearchRotatedSortedArray {public static void main(String[] args) {int[] nums = { 4, 5, 6, 7, 0, 1, 2 };int target = 0;System.out.println(search(nums, target));}static int search(int[] nums, int target) {int low = 0, high = nums.length - 1;// iterate till low is less than highwhile (low <= high) {// calculate mid pointint mid = low + (high - low) / 2;// if target value is same as mid// value then return itif (nums[mid] == target)return mid;// if mid value is less than low valueelse if (nums[mid] < nums[low]) {// if target is greater than mid and target is less than// high than update lowif (target > nums[mid] && target <= nums[high])low = mid + 1;// else update highelsehigh = mid - 1;}// if mid value is greater than highelse if (nums[mid] > nums[high]) {// if target is less than mid and target is greater than// low then update highif (target < nums[mid] && target >= nums[low])high = mid - 1;// else update lowelselow = mid + 1;} else {// update highif (target < nums[mid])high = mid - 1;// else update lowelselow = mid + 1;}}return -1;}}
C++
#include <bits/stdc++.h>using namespace std;int search(vector<int> &nums, int target){int low = 0, high = nums.size() - 1;//iterate till low is less than highwhile (low <= high){//calculate mid pointint mid = low + (high - low) / 2;//if target value is same as mid//value then return itif (nums[mid] == target)return mid;//if mid value is less than low valueelse if (nums[mid] < nums[low]){//if target is greater than mid and target is less than//high than update lowif (target > nums[mid] && target <= nums[high])low = mid + 1;//else update highelsehigh = mid - 1;}//if mid value is greater than highelse if (nums[mid] > nums[high]){//if target is less than mid and target is greater than//low then update highif (target < nums[mid] && target >= nums[low])high = mid - 1;//else update lowelselow = mid + 1;}else{//update highif (target < nums[mid])high = mid - 1;//else update lowelselow = mid + 1;}}return -1;}int main(){vector<int> nums = {4, 5, 6, 7, 0, 1, 2};int target = 0;cout << search(nums, target);return 0;}
No comments:
Post a Comment