Search in Rotated Sorted Array II - LeetCode
C++ Code
class Solution {
public:
bool search(vector<int>& nums, int target) {
int low = 0, high = nums.size()-1;
while(low <= high) {
int mid = low + (high-low)/2;
if(nums[mid] == target) {
return true;
} else if(nums[low] == nums[mid] && nums[mid] == nums[high]) {
low++;
high--;
} else if(nums[low] <= nums[mid]) {
if(nums[low] <= target && target <= nums[mid]) {
high = --mid;
} else {
low = ++mid;
}
} else {
if(nums[mid] <= target && target <= nums[high]) {
low = ++mid;
} else {
high = --mid;
}
}
}
return false;
}
};
TypeScript Code
function search(nums: number[], target: number): boolean {
let low: number = 0;
let high: number = nums.length-1;
while(low <= high) {
let mid: number = low + Math.floor((high-low)/2);
if(nums[mid] == target) {
return true;
} else if(nums[low] == nums[mid] && nums[mid] == nums[high]) {
low++;
high--;
} else if(nums[low] <= nums[mid]) {
if(nums[low] <= target && target <= nums[mid]) {
high = --mid;
} else {
low = ++mid;
}
} else {
if(nums[mid] <= target && target <= nums[high]) {
low = ++mid;
} else {
high = --mid;
}
}
}
return false;
};
Go Code
func search(nums []int, target int) bool {
low := 0;
high := len(nums) - 1;
for low <= high {
mid := low + (high-low)/2;
if nums[mid] == target {
return true;
} else if nums[low] == nums[mid] && nums[mid] == nums[high] {
low++;
high--;
} else if nums[low] <= nums[mid] {
if nums[low] <= target && target <= nums[mid] {
high = mid-1;
} else {
low = mid+1;
}
} else {
if nums[mid] <= target && target <= nums[high] {
low = mid+1;
} else {
high = mid-1;
}
}
}
return false;
}