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

    For those who have already solved Search in Rotated Sorted Array, this problem can be solved similarly using codes for that problem and simply adding codes to skip the duplicates.

    For Search in Rotated Sorted Array, I post solutions in C/C++/Python here (C and C++ only needs 11 lines).

    Now, based on the above codes, you can solve this problem by simply adding two lines to skip duplicates both starting from left and right.

     1 class Solution {
     2 public: 
     3     bool search(vector<int>& nums, int target) {
     4         int l = 0, r = nums.size() - 1;
     5         while (l <= r) {
     6             while (l < r && nums[l] == nums[l + 1]) l++; // skip duplicates from the left
     7             while (r > l && nums[r] == nums[r - 1]) r--; // skip duplicates from the right
     8             int mid = (l + r) / 2;
     9             if (nums[mid] == target) return true; 
    10             if (nums[mid] > target) {
    11                 if (nums[l] <= target || nums[mid] < nums[l]) r = mid - 1;
    12                 else l = mid + 1;
    13             }
    14             else {
    15                 if (nums[l] > target || nums[mid] >= nums[l]) l = mid + 1;
    16                 else r = mid - 1;
    17             }
    18         }
    19         return false;
    20     }
    21 }; 
  • 相关阅读:
    Spring Security 4
    JPA查询
    改进的冒泡算法
    Create User
    COM调用 – VB、PB
    J-Link clone问题
    修复山寨版的J-Link
    C# Web版报表
    HTML/CSS/Javascript代码在线压缩、格式化(美化)工具
    eclipse中字母大小写转换快捷键
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4658580.html
Copyright © 2011-2022 走看看