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 Algorithms 33. Search in Rotated Sorted Array

题目难度: Medium 原题描述: Suppose an array sorted in ascending order is rotated at some pivot unk...

leetcode-33-Search in Rotated Sorted Array

#include #include using namespace std; class Solution { public: /* 旋转数组只能有三种情况: 1. 左...

Leetcode33 Search in Rotated Sorted Array

Search in Rotated Sorted Array Suppose a sorted array is rotated at some pivot unknown to you befo...

【leetcode】No.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 题解

题意简述:给定一个按升序排序的数组,这个数组进行了数次旋转(例如数组[0,1,2,4,5,6,7]在2和4之间执行一次旋转就会变成[4,5,6,7,0,1,2]。需要搜索某个数是否在这个数组里面。数组...

leetcode 33. Search in Rotated Sorted Array

1.题目 Suppose a sorted array is rotated at some ...

[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...

LeetCode 33. Search in Rotated Sorted Array

问题描述: Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 ...

Leetcode 33. Search in Rotated Sorted Array

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

【leetcode】33. Search in Rotated Sorted Array

Difficulty:hard Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i....
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode OJ 33 Search in Rotated Sorted Array
举报原因:
原因补充:

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