浜屽垎鎼滅储

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了浜屽垎鎼滅储相关的知识,希望对你有一定的参考价值。

鏍囩锛?/p>

瀹氫箟灞€閮ㄦ渶灏忕殑姒傚康銆俛rr闀垮害涓?鏃讹紝arr[0]鏄眬閮ㄦ渶灏忋€俛rr鐨勯暱搴︿负N(N>1)鏃讹紝濡傛灉arr[0]<arr[1]锛岄偅涔坅rr[0]鏄眬閮ㄦ渶灏忥紱濡傛灉arr[N-1]<arr[N-2]锛岄偅涔坅rr[N-1]鏄眬閮ㄦ渶灏忥紱濡傛灉0<i<N-1锛屾棦鏈塧rr[i]<arr[i-1]鍙堟湁arr[i]<arr[i+1]锛岄偅涔坅rr[i]鏄眬閮ㄦ渶灏忋€?缁欏畾鏃犲簭鏁扮粍arr锛屽凡鐭rr涓换鎰忎袱涓浉閭荤殑鏁伴兘涓嶇浉绛夛紝鍐欎竴涓嚱鏁帮紝鍙渶杩斿洖arr涓换鎰忎竴涓眬閮ㄦ渶灏忓嚭鐜扮殑浣嶇疆鍗冲彲銆?/div>
public class Solution {
    public static int findPartMin(int[] data,int lo,int hi){
    	while(lo<=hi){
    		int mid = lo+(hi-lo)/2;
    		if(data[mid]<data[mid-1]&&data[mid]<data[mid+1])
    			return mid;
    		else if(data[mid]>data[mid-1])
    			hi = mid-1;
    		else if(data[mid]>data[mid+1])
    			lo = mid+1;
    	}
    	return -1;
    }
    public int getLessIndex(int[] arr) {
    	if(arr.length==1)
    		return 0;
    	else if(arr.length>1){
    		if(arr[0]<arr[1])
    			return 0;
    		else if(arr[arr.length-1]<arr[arr.length-2])
    			return arr.length-1;
    		else
    			return findPartMin(arr,1,arr.length-2);
    	}else
    		return -1;
    }
}

銆€銆€

瀵逛簬涓€涓湁搴忔暟缁刟rr锛屽啀缁欏畾涓€涓暣鏁皀um锛岃鍦╝rr涓壘鍒皀um杩欎釜鏁板嚭鐜扮殑鏈€宸﹁竟鐨勪綅缃€?/p>

缁欏畾涓€涓暟缁?strong>arr鍙婂畠鐨勫ぇ灏?strong>n锛屽悓鏃剁粰瀹?strong>num銆傝杩斿洖鎵€姹備綅缃€傝嫢璇ュ厓绱犲湪鏁扮粍涓湭鍑虹幇锛岃杩斿洖-1銆?/p>

娴嬭瘯鏍蜂緥锛?/div>
[1,2,3,3,4],5,3
杩斿洖锛?
import java.util.*;

public class LeftMostAppearance {
    public int findPos(int[] arr, int n, int num) {
        // write code here
        int left = 0,right = n-1;
    	int pos = -1;
    	while(left<=right){
    		int mid = left+(right-left)/2;
    		if(arr[mid]>num)
    			right = mid-1;
    		else if(arr[mid]<num)
    			left = mid+1;
    		else{
    			pos = mid;
    			right = mid-1;
    		}
    	}
    	return pos;
    }
}

鏈変竴涓湁搴忔暟缁刟rr锛屽叾涓笉鍚湁閲嶅鍏冪礌锛岃鎵惧埌婊¤冻arr[i]==i鏉′欢鐨勬渶宸︾殑浣嶇疆銆傚鏋滄墍鏈変綅缃笂鐨勬暟閮戒笉婊¤冻鏉′欢锛岃繑鍥?1銆?/p>

缁欏畾鏈夊簭鏁扮粍arr鍙婂畠鐨勫ぇ灏?strong>n锛岃杩斿洖鎵€姹傚€笺€?/p>

娴嬭瘯鏍蜂緥锛?/div>
[-1,0,2,3],4
杩斿洖锛?
import java.util.*;

public class Find {
    public int findPos(int[] arr, int n) {
        // write code here
        int left = 0,right = n-1;
    	while(left<=right){
    		int mid = left+(right-left)/2;
            if(arr[left]==left)
    			return left;
    		if(arr[mid]>mid)
    			right = mid-1;
    		else if(arr[mid]<mid)
    			left = mid+1;
    		else
    			return mid;
    	}
    	return -1;
    }
}

銆€銆€

以上是关于浜屽垎鎼滅储的主要内容,如果未能解决你的问题,请参考以下文章

浜屽弶鏍戠殑搴忓垪鍖栦笌鍙嶅簭鍒楀寲

hdu2336 (鍖堢墮鍒╂渶澶у尮閰?浜屽垎)

Golang-鏌ユ壘(浜屽垎娉曟煡鎵?

CF 1370D 浜屽垎 2e5

鎼滅储鎻掑叆浣嶇疆