
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Search in Rotated Sorted Array II in C++
Consider we have an array sorted in ascending order. That is rotated at some pivot unknown to us beforehand. For example, if the array is like [0,0,1,2,2,5,6], this might become [2,5,6,0,0,1,2]. We have a target value to search. If that is found in the array, then return true, otherwise return false. So if the array is like [2,5,6,0,0,1,2], and target is 0, then the output will be 0
Let us see the steps −
low := 0 and high := size of array
while low < high
mid := low + (high - low)/2
if nums[mid] = target, then return true
if nums[low] = nums[mid] and nums[high - 1] = nums[mid], then
increase low by 1 and decrease high by 1, and continue for the next iteration
if nums[low] <= nums[mid], then
if target >= nums[low] and target < nums[mid], then high := mid, otherwise low := mid + 1
Otherwise
if target <= nums[high - 1] and target > nums[mid], then low := mid + 1, otherwise high := mid
return false
Example
Let us see the following implementation to get better understanding −
class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ low = 0 high = len(nums) while low<high: mid = low + (high-low)//2 print(mid) if nums[mid] == target: return True if nums[low] == nums[mid] and nums[high-1] == nums[mid]: low +=1 high -=1 continue if nums[low]<=nums[mid]: if target >=nums[low] and target <nums[mid]: high = mid else: low = mid+1 else: if target<=nums[high-1] and target>nums[mid]: low = mid+1 else: high = mid return False
Input
[2,5,6,0,0,1,2] 0
Output
true
- Related Articles
- Search in Rotated Sorted Array II in Python
- Search in Rotated Sorted Array in Python
- Find Minimum in Rotated Sorted Array II in C++
- C++ program to search an element in a sorted rotated array
- Find Minimum in Rotated Sorted Array in C++
- Find the Rotation Count in Rotated Sorted array in C++
- Maximum element in a sorted and rotated array in C++
- Check if an array is sorted and rotated in Python
- Check if an array is sorted and rotated in C++
- Finding smallest element in a sorted array which is rotated in JavaScript
- Program to check whether an array Is sorted and rotated in Python
- Search elements in a sorted object array in Java
- Convert Sorted Array to Binary Search Tree in Python
- Search in a Sorted Array of Unknown Size in C++
- Count rotations in sorted and rotated linked list in C++
