C++實現(xiàn)LeetCode(81.在旋轉(zhuǎn)有序數(shù)組中搜索之二)
[LeetCode] 81. Search in Rotated Sorted Array II 在旋轉(zhuǎn)有序數(shù)組中搜索之二
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.
Example 1:
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
Example 2:
Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false
Follow up:
- This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
- Would this affect the run-time complexity? How and why?
這道是之前那道 Search in Rotated Sorted Array 的延伸,現(xiàn)在數(shù)組中允許出現(xiàn)重復數(shù)字,這個也會影響我們選擇哪半邊繼續(xù)搜索,由于之前那道題不存在相同值,我們在比較中間值和最右值時就完全符合之前所說的規(guī)律:如果中間的數(shù)小于最右邊的數(shù),則右半段是有序的,若中間數(shù)大于最右邊數(shù),則左半段是有序的。而如果可以有重復值,就會出現(xiàn)來面兩種情況,[3 1 1] 和 [1 1 3 1],對于這兩種情況中間值等于最右值時,目標值3既可以在左邊又可以在右邊,那怎么辦么,對于這種情況其實處理非常簡單,只要把最右值向左一位即可繼續(xù)循環(huán),如果還相同則繼續(xù)移,直到移到不同值為止,然后其他部分還采用 Search in Rotated Sorted Array 中的方法,可以得到代碼如下:
class Solution { public: bool search(vector<int>& nums, int target) { int n = nums.size(), left = 0, right = n - 1; while (left <= right) { int mid = (left + right) / 2; if (nums[mid] == target) return true; if (nums[mid] < nums[right]) { if (nums[mid] < target && nums[right] >= target) left = mid + 1; else right = mid - 1; } else if (nums[mid] > nums[right]){ if (nums[left] <= target && nums[mid] > target) right = mid - 1; else left = mid + 1; } else --right; } return false; } };
到此這篇關于C++實現(xiàn)LeetCode(81.在旋轉(zhuǎn)有序數(shù)組中搜索之二)的文章就介紹到這了,更多相關C++實現(xiàn)在旋轉(zhuǎn)有序數(shù)組中搜索之二內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
探討編寫int strlen(char *strDest);不允許定義變量的問題
本篇文章是對編寫int strlen(char *strDest);不允許定義變量的問題進行了詳細的分析介紹,需要的朋友參考下2013-05-05c語言中g(shù)etch,getche,getchar的區(qū)別
getche() 和getch()很相似,它也需要引入頭文件conio.h,那它們之間的區(qū)別又在哪里呢?不同之處就在于getch()無返回顯示,getche()有返回顯示2013-09-09Visual Studio Code (vscode) 配置 C / C++ 環(huán)境的流程
這篇文章主要介紹了Visual Studio Code (vscode) 配置 C / C++ 環(huán)境的流程,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09