1. 程式人生 > 其它 >leetcode——搜尋旋轉排序陣列

leetcode——搜尋旋轉排序陣列

技術標籤:面試C++

題目:

升序排列的整數陣列nums在預先未知的某個點上進行了旋轉(例如,[0,1,2,4,5,6,7]經旋轉後可能變為[4,5,6,7,0,1,2])。請你在陣列中搜索target,如果陣列中存在這個目標值,則返回它的索引,否則返回-1。(https://leetcode-cn.com/problems/search-in-rotated-sorted-array/

示例

1、輸入:nums = [4,5,6,7,0,1,2], target = 0    輸出:4
2、輸入:nums = [4,5,6,7,0,1,2], target = 3    輸出:-1

提示:

  • 1 <= nums.length <= 5000
  • -10^4 <= nums[i] <= 10^4
  • nums 中的每個值都 獨一無二
  • nums 肯定會在某個點上旋轉
  • -10^4 <= target <= 10^4

方案:二分法

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

時間複雜度O(log^n)

空間複雜度O(1)

注意:旋轉右側所有元素小於nums[0]