zoukankan      html  css  js  c++  java
  • Java for LeetCode 081 Search in Rotated Sorted Array II

    Follow up for "Search in Rotated Sorted Array":
    What if duplicates are allowed?

    Would this affect the run-time complexity? How and why?

    Write a function to determine if a given target is in the array.

    解题思路:

    参考Java for LeetCode 033 Search in Rotated Sorted Array 修改下代码即可,JAVA实现如下:

        public boolean search(int[] nums, int target) {
    		int left = 0, right = nums.length - 1;
    		while (left <= right) {
    			if (target == nums[(right + left) / 2])
    				return true;
    			// 右半部分为旋转区域
    			if (nums[(right + left) / 2] > nums[left]) {
    				if (target >= nums[left] && target < nums[(right + left) / 2])
    					right = (right + left) / 2 - 1;
    				else
    					left = (right + left) / 2 + 1;
    			}
    			// 左半部分为旋转区域
    			else if (nums[(right + left) / 2] < nums[left]) {
    				if (target > nums[(right + left) / 2] && target <= nums[right])
    					left = (right + left) / 2 + 1;
    				else
    					right = (right + left) / 2 - 1;
    			} 
    			// 老实遍历
    			else
    				left++;
    		}
    		return false;
        }
    
  • 相关阅读:
    数论学习之乘法逆元
    数论学习之扩展欧几里得
    数论学习之费马与欧拉
    一次函数
    东南西北
    接水问题
    脱水缩合
    背单词
    单词接龙
    字符串,字符数组
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4513940.html
Copyright © 2011-2022 走看看