Search in Rotated Sorted Array

来源:互联网 发布:floyd算法实验总结 编辑:程序博客网 时间:2024/05/23 14:10

描述
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.

中文
轮换排序的数组,给你一个目标值,找到目标值的索引号。
假设数组中没有重复的元素。

分析:
使用二分查找,找到中间值,和起始值进行比较,如果中间值小于起始值,则说明右面有序。否则左面有序,这样继续用二分查找进行。

class Solution {public:    int search(vector<int>& nums, int target) {     int n;     n=nums.size();     if(n==0)     return -1;     int low,high;     low=0;high=n-1;     while(low<high)  //错误 可以用low!=high作为结束条件     {      mid=(low+high)/2;//求中值一定要注意     if(target==nums[mid])     return mid;     if(nums[low]<nums[mid]){//用小于等于说明转折点在右半部分         if(targent<nums[mid])         target必须同时限定在两个边界内才可以。           high=mid;         esle           low=mid;           }     else{         if(targent>nums[mid])         low=mid;         esle         high=mid;         }     }     return -1;    }};

二分查找算法不熟悉,需要加强训练,边界问题,需要注意
正确的:

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

Runtime: 8 ms

0 0
原创粉丝点击