LeetCode——033
来源:互联网 发布:javascript 显示隐藏 编辑:程序博客网 时间:2024/06/13 08:28
/*
33. Search in Rotated Sorted Array My Submissions QuestionEditorial Solution
Total Accepted: 98590 Total Submissions: 326117 Difficulty: Hard
Suppose a sorted array 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.
Subscribe to see which companies asked this question
*/
/*
解题思路:
旋转数组的元素查找,依然采用折半查找
比非旋转数组多了一层判断
if(右半边有序){
if(target在右半边){
left=mid+1;
}
else{
right=mid-1;
}
//左半边有序
}else{
if(target在左半边){
right=mid-1;
}
else{
left=mid+1;
}
}
*/
class Solution {public: int search(vector<int>& nums, int target) { //旋转数组中查找数字,使用折半查找法 if(nums.empty())return -1; int left=0,right=nums.size()-1; int mid; while(left<=right){ mid=left+(right-left)/2; if(nums[mid]==target)return mid; //右半边有序 else 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; }};
- LeetCode——033
- 开始刷刷Leetcode—leetcode第二题
- LeetCode —— Combinations
- LeetCode —— Triangle
- LeetCode —— Anagrams
- [leetcode] Subsets——@
- Permutations——LeetCode
- minimum_window_substring ——leetcode
- LeetCode——Candy
- LeetCode——Triangle
- LeetCode——Combinations
- LeetCode——Permutations
- *candy——leetcode
- gas_station——leetcode
- LeetCode——Candy
- LeetCode——Triangle
- LeetCode——Anagrams
- LeetCode——Subsets
- 李商隐 无题
- 关于沸点
- p1057 金明的预算方案
- Servlet 表单数据
- Three.js打造H5里的“3D全景漫游”秘籍
- LeetCode——033
- java 泛型实现Dao 操作的重用
- 单例模式
- JDK容器与并发—Queue—DelayQueue
- oil deposits——深搜
- 199. Binary Tree Right Side View
- Swift的动态性
- Catalan数——卡特兰数
- 代码重构何时是个头?