eng
competition

Text Practice Mode

C++ code (Practice keywords and characters)

created Jan 24th 2024, 11:03 by FachoAlee


0


Rating

196 words
3 completed
00:00
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
 
nt PivotIndex(vector<int>& nums) {
 
        int size = nums.size();
        int start = 0;
        int end = size-1;
        int pivotIndex = 0;
        while (start<=end)
        {
            int mid = start + (end-start) / 2;
            if(start==end)
            {
                pivotIndex = start;
                break;
            }
            else if ( (mid+1) <size && nums[mid]  > nums[mid+1])
            {
                pivotIndex = mid;
                 break;
            }
            else if (mid-1 >=  && nums[mid] < nums[mid-1])
            {
                pivotIndex = mid-1;
                break;
            }
            else if (nums[mid] < nums[start])
            {
                end = mid-1;
            }
            else
            {
                start = mid + 1;
            }
        }
          
           return pivotIndex;
      
    }
      
     int binarySearch(vector<int> arr, int start, int end, int target)
     {
          int store = -1;
         while (start<=end)
         {
         int mid = start + (end-start) /2;
         if(arr[mid] == target)
         {
             store = mid;
             break;
         }
         else if (arr[mid] < target)
         {
             start = mid + 1;
         }
         else  
         {
             end = mid -1;
         }
      }
          return store;   
     }
      
     int search(vector<int> &nums,int target)
     {
         int size = nums.size();
            int result = -1;
         int Pivot = PivotIndex(nums);
 
         if(target >= nums[0] && target <= nums[Pivot])
         {
            result = binarySearch(nums, 0, Pivot, target);
         }
         else  
         {
             result = binarySearch(nums, Pivot+1, size-1, target);
         }
 
            return result;
     }

saving score / loading statistics ...