1. 程式人生 > >網際網路校招常考經典演算法模板彙總(java && )

網際網路校招常考經典演算法模板彙總(java && )

一、二分查詢
1、左閉右閉版[start, end]
(1)迴圈實現:

bool binarySearch(int arr[ ], int start, int end, int target){
	while(start<=end){//左閉右閉是小於等於
		int  mid = (start+end)/2;
		int  t = arr[mid];
		if (t == target) return ture;
		else if (t > target) end = mid-1; 
			 else start = mid+1;
	}
	return false;
}

(2)遞迴實現:

bool binarySearch(int arr[ ], int start, int end, int target){
	if (start<=end){//左閉右閉是小於等於
		int  mid = (start+end)/2;
		int  t = arr[mid];
		if (t == target) return ture;
		else if (t > target) return binarySearch(arr, start, mid-1, target);
			 else return return binarySearch(
arr, mid+1, end, target); }else return false; }

2、左閉右開版[start, end)
(1)迴圈實現:

bool binarySearch(int arr[ ], int start, int end, int target){
	while(start<end){//左閉右開是小於
		int  mid = (start+end)/2;
		int  t = arr[mid];
		if (t == target) return ture;
		else if (t > target) end = mid; //多減1錯誤
			 else
start = mid+1;//不加1容易死迴圈 } return false; }

(2)遞迴實現:

bool binarySearch(int arr[ ], int start, int end, int target){
	if (start<end){//左閉右閉是小於等於
		int  mid = (start+end)/2;
		int  t = arr[mid];
		if (t == target) return ture;
		else if (t > target) return binarySearch(arr, start, mid, target);
			 else return return binarySearch(arr, mid+1, end, target);
	}else return false;
}