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

    Suppose a sorted array is rotated at some pivot unknown to you beforehand.

    (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

    You are given a target value to search. If found in the array return its index, otherwise return -1.

    You may assume no duplicate exists in the array.

    解题思路:

    Tag中已经有提示用二分查找,关键是确定target在左半部分还是右半部分,建议画个图,能直观很多。

    JAVA实现如下:

    	static public int search(int[] nums, int target) {
    		int left = 0, right = nums.length - 1;
    		while (left <= right) {
    			if (target == nums[(right + left) / 2])
    				return (right + left) / 2;
    			//右半部分为旋转区域
    			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 (target > nums[(right + left) / 2] && target <= nums[right])
    					left = (right + left) / 2 + 1;
    				else
    					right = (right + left) / 2 - 1;
    			}
    		}
    		return -1;
    	}
    
  • 相关阅读:
    setTimeout详解
    【康娜的线段树】
    【[CQOI2016]手机号码】
    【[IOI2014]Wall 砖墙】
    【[1007]梦美与线段树】
    【[POI2010]ANT-Antisymmetry】
    【[HEOI2016/TJOI2016]排序】
    【[SCOI2016]背单词】
    【[HNOI2008]GT考试】
    【[JSOI2007]建筑抢修】
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4486064.html
Copyright © 2011-2022 走看看