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 }; 
  • 相关阅读:
    白话插件框架原理
    C# 可扩展编程MEF学习
    C#依赖注入实例
    迷你版AOP框架
    AOP 面向切面编程
    C++ 面向对象
    c++ 的异常处理
    C++ 模板 template
    c 二维数组动态分配和释放
    C++ 指针二维数组, C++二维指针数组笔记
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4658580.html
Copyright © 2011-2022 走看看