Search In Rotated Array II Problem Solution

Search In Rotated Array II : There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).

Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4].

Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums.

Example :

Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true

Search In Rotated Array II Problem Solution

Problem Solution In Python

class Solution:
    def search(self, nums: List[int], target: int) -> bool:
        pivot=0
        for ar in range(len(nums)-1):
            if nums[ar]>nums[ar+1]:
                pivot=ar+1
                break
        nums = nums[pivot:]+nums[0:pivot]
        left=0
        right=len(nums)-1
        while left<=right:
            mid = int((left+right)/2)
            if nums[mid]==target:
                return True
            elif nums[mid]>target:
                right=mid-1
            else:
                left=mid+1
        return False

Problem Solution In Java

class Solution {
    public boolean search(int[] nums, int target) 
    {
       
        for(int i=0;i<nums.length;i++)
        {
            if(nums[i]==target)
                return true;
        }
        return false;
    }
}

Problem Solution In C++

class Solution {
public:
    bool search(const vector<int>& nums, int target) {
        for (const auto& i : nums) {
            if (i == target) {
                return true;
            }
        }
        return false;
    }
};


Problem Solution In C

bool search(int* nums, int numsSize, int target){
    int n = 0;
    while (n < numsSize) {
        if (nums[n] < target) {
            n++;
        } else if (nums[n] == target) {
            return true;
        } else {
            break;
        }
    }
    if (n != 0) {
        return false;
    } else {
        int end = numsSize - 1;
        while (end > n) {
            if (nums[end] > target) {
                end--;
            }else if (nums[end] == target) {
                return true;
            } else {
                return false;
            }
        }
    }
    return false;
}

If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment