Header Ad

Leetcode Search in Rotated Sorted Array II problem solution

In this Leetcode Search in Rotated Sorted Array II problem solution, 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 the target is in nums, or false if it is not in nums. You must decrease the overall operation steps as much as possible.

Leetcode Search in Rotated Sorted 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;
}


Post a Comment

0 Comments