Algorithms practice:leetcode 33. Search in Rotated Sorted Array

Algorithms practice:leetcode33 Search in Rotated Sorted Array

Description

There is an integer array nums sorted in ascending order (with distinct values).

Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= 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,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].

Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

You must write an algorithm with O(log n) runtime complexity.

Example

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0

Output: 4

Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3

Output: -1

Example 3:

Input: nums = [1], target = 0

Output: -1

Constraints

Constraints:

1 <= nums.length <= 5000

-104 <= nums[i] <= 104

All values of nums are unique.

nums is an ascending array that is possibly rotated.

-104 <= target <= 104

code

cpp 复制代码
class Solution {
public:
    int search(vector<int>& nums, int target) {
        int left =0;
        int right = nums.size()-1;

        while(left<=right)
        {
            int mid = (left+right)/2;
             if (nums[mid] == target)
            {
                return mid;
            }
            if(nums[left] <=nums[mid]) // [left , mid] order subarray
            {
                if(nums[left] <=target && target< nums[mid])
                {
                    right = mid-1;
                }
                else//( target> nums[mid] || target< nums[right])
                {
                    left = mid+1;
                }

            }
            else
            {
                // [mid , right] order subarray
                if(nums[mid] <target && target<= nums[right])
                {
                    left = mid+1;
                }
                else //( target> nums[mid] || target< nums[right])
                {
                     right = mid-1;
                }

            }
        }
        return -1;
    }
};

Oral process of solving problems

pivot index k = 0 0 1 2 3 4 5 6

pivot index k = 1 1 2 3 4 5 6 0

pivot index k = 2 2 3 4 5 6 0 1

pivot index k = 3 3 4 5 6 0 1 2

pivot index k = 4 4 5 6 0 1 2 3

pivot index k = 5 5 6 0 1 2 3 4

pivot index k = 6 6 0 1 2 3 4 5

pivot index k = 0 0 1 2 3 4 5 6

The problem requires a runtime complexity of O(log n), which can be achieved by using binary search. The main idea is to divide the search space into two halves using the middle element. If the middle element is the target, the process terminates. If not, we decide which subarray to continue the search in. The key to the problem is how to choose the subarray.

The 'nums' array may be rotated at an unknown pivot index 'k'. The pivot indices are listed from 0 to 6 in the rotated arrays above. All possible rotated results can be seen. The origin array should be separated into two ascending arrays. If the array is split into two equal parts, there must be an ascending subarray.

For example, if the pivot index k = 2 [2 3 4 5 6 0 1],and target is 3, we select index 3 as the middle element.

The sub-array to the left of the middle item is [2 3 4 5], and the sub-array to the right of the middle item is [6 0 1].

The first sub-array is in ascending order, and we can determine if the target is in this array. In this case, the target is 3, which satisfies the conditions 2<3 and 3<5. Therefore, the target must be in this sub-array. If it is, we select this sub-array in the next iteration. Otherwise, we choose a different approach.

Therefore, to decide on a subarray, we must first find the subarray in order and check whether the target is in this array. If it is, we choose this subarray. If not, we choose another subarray.

now write code:

firstly, we declare two int variables as Pointers: a left pointer and a right pointer and assign 0 to left point ,assign nums.size()-1 to right point .

we declare

cpp 复制代码
int left =0;
int right = nums.size()-1;

we use while loop. In each iteration , we check whether a subarray is order? if nums[left] <=nums[mid], the subarray from left to mid is order subarray. then if target in this subarray , we move right to mid -1. otherwise, we move left to mid+1

if above requirement is not meet, we can say the subarray from mid to right is order subarray. then if target in this subarray , we move left to mid+1. otherwise, we move right to mid -1...

Time Complexity: The time complexity is O(log⁡n) since we're performing a binary search over the elements of the array.

Space Complexity: The space complexity is O(1) because we only use a constant amount of space to store our variables (left\text{left}left, right\text{right}right, mid\text{mid}mid), regardless of the size of the input array.

words

Initialization is the process of assigning a value to the Variable. [2]

Declare and initialize a variable with an integer value [3]

binary search 二分搜索算法

terminate 终止(进程)

subarray

ascending

iteration迭代

pointer 指针

we declare two int variables 申明变量

assign 0 to left point 赋值

https://leetcode.com/problems/search-in-rotated-sorted-array/description/

  1. C++ Variables
  2. https://www.learncpp.com/cpp-tutorial/variable-assignment-and-initialization/
  3. https://www.codeease.net/programming/python/Declaration-and-Initialization-of-Variables
  4. https://leetcode.com/problems/search-in-rotated-sorted-array/solutions/3879263/100-binary-search-easy-video-o-log-n-optimal-solution/
相关推荐
jiao_mrswang19 分钟前
leetcode-18-四数之和
算法·leetcode·职场和发展
qystca28 分钟前
洛谷 B3637 最长上升子序列 C语言 记忆化搜索->‘正序‘dp
c语言·开发语言·算法
薯条不要番茄酱28 分钟前
数据结构-8.Java. 七大排序算法(中篇)
java·开发语言·数据结构·后端·算法·排序算法·intellij-idea
今天吃饺子33 分钟前
2024年SCI一区最新改进优化算法——四参数自适应生长优化器,MATLAB代码免费获取...
开发语言·算法·matlab
是阿建吖!34 分钟前
【优选算法】二分查找
c++·算法
王燕龙(大卫)38 分钟前
leetcode 数组中第k个最大元素
算法·leetcode
不去幼儿园2 小时前
【MARL】深入理解多智能体近端策略优化(MAPPO)算法与调参
人工智能·python·算法·机器学习·强化学习
Mr_Xuhhh2 小时前
重生之我在学环境变量
linux·运维·服务器·前端·chrome·算法
盼海3 小时前
排序算法(五)--归并排序
数据结构·算法·排序算法
网易独家音乐人Mike Zhou6 小时前
【卡尔曼滤波】数据预测Prediction观测器的理论推导及应用 C语言、Python实现(Kalman Filter)
c语言·python·单片机·物联网·算法·嵌入式·iot