Skip to main content

Search in Rotated Sorted Array

二分题,先多写点判断再压缩状态就可以得到非常简短的代码了Ologn&O1

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