33. Search in Rotated Sorted Array
生活随笔
收集整理的這篇文章主要介紹了
33. Search in Rotated Sorted Array
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
description:
一個(gè)數(shù)列,不知道在哪翻轉(zhuǎn)了一下,現(xiàn)在給定一個(gè)值,如果他在這個(gè)翻轉(zhuǎn)后的數(shù)列里, return 它對(duì)應(yīng)的 index
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Note:
Example:
Example 1:Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4Example 2:Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1answer:
class Solution { public:int search(vector<int>& nums, int target) {int left = 0, right = nums.size() - 1;while (left <= right) {int mid = left + (right - left) / 2;if (nums[mid] == target) return mid;if (nums[mid] < nums[right]) {//較之于普通的二分查找,增加了中軸值得判斷if (nums[mid] < target && nums[right] >= target) left = mid + 1;else right = mid - 1;} else {if (nums[mid] > target && nums[left] <= target) right = mid - 1;else left = mid + 1;}}return -1;} };relative point get√:
hint :
轉(zhuǎn)載于:https://www.cnblogs.com/forPrometheus-jun/p/11095370.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的33. Search in Rotated Sorted Array的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: eclipse修改项目访问前缀
- 下一篇: 笔记:类加载器