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;
    	}
    
  • 相关阅读:
    OpenJudge 6042 雇佣兵
    POJ 1741 树上 点的 分治
    Codevs 1695 Windows2013
    复制书稿
    乘积最大
    编辑距离问题
    石子合并
    最大正方形子矩阵
    选菜
    混合背包
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4486064.html
Copyright © 2011-2022 走看看