LeetCode OJ 33 Search in Rotated Sorted Array

原创 2015年07月06日 18:21:08

难度:hard

由此可见leetcode的hard难度比较于acm是偏简单一些的。

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.

解题思路:采用二分法查找是核心。由于数列的变换是在有序数列的基础上,则假如在二分时若一半无序则另一半会有序,判断逻辑放在有序的一侧即可。注意边界值,不要迷信AC的案例代码,因为我个人测试过一些ac代码在边界情况时会出现错误。

代码如下:

class Solution {
public:
    int search(vector<int>& nums, int target) {
		int first=0;
		int last=nums.size()-1;
		while(first!=last)
		{
			const int mid=first+(last-first)/2;
			if(nums[mid]==target)
				return mid;
			if(nums[first]<=nums[mid])
			{
				if(nums[first]<=target&&target<nums[mid])
					last=mid;
				else
					first=mid+1;
			}
			else
			{
				if(nums[mid]<target&&target<=nums[last])
					first=mid+1;
				else
					last=mid;
			}
		}
		if(nums[last]==target)
			return last;
		else
			return -1;
        
    }
};
运行时间:4ms

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

leetcode(33). Search in Rotated Sorted Array

problem Suppose an array sorted in ascending order is rotated at some pivot unknown to you befo...

leetcode 33. Search in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 mig...

leetcode解题之33&81. Search in Rotated Sorted Array java版(在旋转的数字中查找指定值)

33. Search in Rotated Sorted Array ,81. Search in Rotated Sorted Array II 。 leetcode解题之33&81. Search...

[leetcode] 33. Search in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 mig...

leetcode 33. Search in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 mig...

leetcode 33. Search in Rotated Sorted Array

题目大意:一个排序数组绕某个数选择了,在这个旋转后的数组中找指定的元素target 找到就返回在数组中的序号,否则返回-1 解题思路: 1、当然是可以直接搜的(复杂度O(n)),也可以过.但是对于有一...

Leetcode 33. Search in Rotated Sorted Array

题目如下: Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand...

Leetcode 33 - Search in Rotated Sorted Array(二分)

题意给一个有序数组,然后从数组的某一个位置,将前后两半交换。现在给一个数k,求k在数组中出现的位置,如果没有出现,返回-1。思路算法1画个图,其实就两种情况:前半段长还是后半段长,然后分若干种情况去讨...
  • Lzedo
  • Lzedo
  • 2017-02-13 16:44
  • 88

【C++】【LeetCode】33. Search in Rotated Sorted Array

题目Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i...

LeetCode33——Search in Rotated Sorted Array

LeetCode33——Search in Rotated Sorted Array 简单来说就是在数组中查找  输入的  target,如果找到返回索引,如果没有找到返回-1 在中S...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)