Skip to content

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

Open

Description

@resse92

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

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;
    }
};

Activity

  1. changed the title [-]f[/-] [+]LeetCode: 33. 搜索旋转排序数组[/+] on Jun 3, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions