zoukankan      html  css  js  c++  java
  • [leetcode]81. Search in Rotated Sorted Array II旋转过有序数组里找目标值II(有重)

    This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.

    思路

    该题是[leetcode]33. Search in Rotated Sorted Array旋转过有序数组里找目标值 的followup

    唯一区别是加了line24-26的else语句来skip duplicates

    代码

     1 class Solution {
     2     public boolean search(int[] nums, int target) {
     3          // corner case
     4         if (nums.length == 0) return false;
     5         // init
     6         int left = 0;
     7         int right = nums.length - 1;
     8 
     9         while (left <= right) {
    10             int mid = left + (right - left) / 2;
    11             if (nums[mid] == target) return true;
    12             else if (nums[mid] < nums[right]) { // right side is sorted
    13                 if (target > nums[mid] && target <= nums[right]) {
    14                     left = mid + 1;
    15                 } else {
    16                     right = mid - 1;
    17                 }
    18             } else if(nums[mid] > nums[right]){ // left side is sorted 
    19                 if (target < nums[mid] && target >= nums[left]) {
    20                     right = mid - 1;
    21                 } else {
    22                     left = mid + 1;
    23                 }
    24             }else{
    25                right--; //skip duplicats 
    26             }
    27         }
    28         return false;
    29     }   
    30 }
  • 相关阅读:
    ejs
    appcan.slider.js探索
    js语法重点
    canvas动画
    canvas绘图
    Bootstrap 表单
    模态框
    Node.js EventEmitter(事件队列)
    Node.js 事件循环
    react native 页面跳转
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9828237.html
Copyright © 2011-2022 走看看