Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode: 33. 搜索旋转排序数组 #78

Open
resse92 opened this issue May 30, 2018 · 0 comments
Open

LeetCode: 33. 搜索旋转排序数组 #78

resse92 opened this issue May 30, 2018 · 0 comments

Comments

@resse92
Copy link
Owner

resse92 commented May 30, 2018

二分查找法,注意左右边界的确定。

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int first = 0, last = nums.size();
        
        while (first != last) {
            const int mid = (first + last) / 2;
            if (nums[mid] == target) {
                return mid;
            } else 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 - 1]) {
                    first = mid + 1;
                } else {
                    last = mid;
                }
            }
        }
        return -1;
    }
};
@resse92 resse92 changed the title f LeetCode: 33. 搜索旋转排序数组 Jun 3, 2018
@resse92 resse92 added Leetcode and removed iOS labels Jun 3, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant