码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode[33]-Search in Rotated Sorted Array

时间:2015-06-11 11:08:14      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:search   sorted   return   index   pivot   

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.


方法一:直接for循环求解

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int n = nums.size();

        for(int i = 0; i<n; i++){
            if(nums[i] == target) return i;
        }
        return -1;
    }
};

方法二:二分搜索求解
分析:从中点处划分,左右两边一定有一部分是有序的,对于有序的分别做判断。

class Solution {
public:
    int search(vector<int>& nums, int target) {

        int i = 0, j = nums.size()-1;

        while(i<=j){
            int mid = (i+j)/2;

            if(nums[mid] == target) 
                return mid;
            //if left is sorted
            else if(nums[i] <= nums[mid]){
                if(nums[i] <= target && target < nums[mid]) 
                    j = mid-1;
                else
                    i = mid + 1;
            }else {
                if(nums[mid] < target && target <= nums[j] ) 
                    i = mid +1;
                else 
                    j = mid-1;
            }
        }
        return -1;
    }
};

Leetcode[33]-Search in Rotated Sorted Array

标签:search   sorted   return   index   pivot   

原文地址:http://blog.csdn.net/dream_angel_z/article/details/46454093

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!