leetcode:Search in Rotated Sorted Array
生活随笔
收集整理的這篇文章主要介紹了
leetcode:Search in Rotated Sorted Array
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目要求:
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.
題目地址:https://leetcode.com/problems/search-in-rotated-sorted-array/
?
public class Solution {public static int search(int[] A, int target) {int first=0,last=A.length-1,mid;while(first<=last){mid=(first+last)/2;System.out.println("當(dāng)前搜索范圍"+A[first]+"--"+A[last]+",mid="+A[mid]);if(A[mid]==target)return mid;else if(A[first]<=A[mid]){//左有序if(target<A[first]||target>A[mid]){first=mid+1;}else{last=mid-1;}}else{//右有序if(target<A[mid]||target>A[last]){last=mid-1;}else{first=mid+1;}}}return -1;} }
POINTS:和傳統(tǒng)2分查找無(wú)差別,只是通過(guò)A[mid]與A[first]A[last]的大小比較確定翻轉(zhuǎn)的奇異點(diǎn)在2段范圍中的哪一段,在對(duì)正常有序的那一段判斷下目標(biāo)在不在其中。
轉(zhuǎn)載于:https://www.cnblogs.com/charlesdoit/p/4324148.html
總結(jié)
以上是生活随笔為你收集整理的leetcode:Search in Rotated Sorted Array的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 00后微信网名
- 下一篇: Linux Terminal 控制终端的