zoukankan      html  css  js  c++  java
  • [LeetCode] Search in Rotated Sorted Array

    This problem is a nice application of binary search. The key lies in how to determine the correct half for target. Since the array has been rotated, we now need to make some additional checks.

    You may run the following code with some examples to see how it works :-)


    C (0ms)

     1 int search(int* nums, int numsSize, int target) {
     2     int l = 0, r = numsSize - 1;
     3     while (l <= r) {
     4         int mid = (l & r) + ((l ^ r) >> 1);
     5         if (nums[mid] == target) return mid; 
     6         if (nums[mid] > target) {
     7             if (nums[l] <= target || nums[mid] < nums[l]) r = mid - 1;
     8             else l = mid + 1;
     9         }
    10         else {
    11             if (nums[l] > target || nums[mid] >= nums[l]) l = mid + 1;
    12             else r = mid - 1;
    13         }
    14     }
    15     return -1;
    16 }

    C++ (4ms)

     1 class Solution {
     2 public:
     3     int search(vector<int>& nums, int target) {
     4         int l = 0, r = nums.size() - 1;
     5         while (l <= r) {
     6             int mid = (l & r) + ((l ^ r) >> 1);
     7             if (nums[mid] == target) return mid;
     8             if (nums[mid] > target) {
     9                 if (nums[l] <= target || nums[mid] < nums[l]) r = mid - 1;
    10                 else l = mid + 1;
    11             } 
    12             else {
    13                 if (nums[l] > target || nums[mid] >= nums[l]) l = mid + 1;
    14                 else r = mid - 1;
    15             }
    16         }
    17         return -1;
    18     }
    19 };

    Python (40ms)

     1 class Solution:
     2     # @param {integer[]} nums
     3     # @param {integer} target
     4     # @return {integer}
     5     def search(self, nums, target):
     6         l, r = 0, len(nums) - 1
     7         while l <= r:
     8             mid = (l & r)  + ((l ^ r) >> 1)
     9             if nums[mid] == target: 
    10                 return mid
    11             if nums[mid] > target:
    12                 if nums[l] <= target or nums[mid] < nums[l]:
    13                     r = mid - 1
    14                 else:
    15                     l = mid + 1
    16             else:
    17                 if nums[l] > target or nums[mid] >= nums[l]:
    18                     l = mid + 1
    19                 else:
    20                     r = mid - 1
    21         return -1
  • 相关阅读:
    Luogu P4002 [清华集训2017]生成树计数
    Luogu P3978 [TJOI2015]概率论
    Codechef JADUGAR2 Chef and Same Old Recurrence 2
    Codechef TREDEG Trees and Degrees
    一些有趣的数
    有向图上Euler回路计数
    P5105 不强制在线的动态快速排序
    二分图小结
    BZOJ2648: SJY摆棋子
    P3231 [HNOI2013]消毒
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4657810.html
Copyright © 2011-2022 走看看