/** * https://leetcode.cn/problems/sqrtx/description/ * 二分查找 * 将数据分成两部分 * 第一部分为平方小于等于target * 另外的为大于target * left=mid。right=mid-1;使用+1求中 * */ public static void hanShu19(int x){ if (x==0){ return; } long left=1,right=x; while (left<right){ long mid=left+(right-left+1)/2; if (mid*mid<=x)left=mid; else right=mid-1; } System.out.println(left); }
/** * https://leetcode.cn/problems/peak-index-in-a-mountain-array/description/ * 找到山脉的顶 * 由于山顶天然的将数组分成了两端,一段为arr[mid]>arr[mid-1]包括峰顶的左边 * 还有一段为arr[i]>arr[i+1]的右边 * 当arr[mid]>arr[mid-1]的时候说明mid落在了左边此时left=mid * 反之则落在了右边right=mid-1 * */ public static void hanShu21(int[] arr){ int left=1,right=arr.length-2; while (left<right){ int mid=left+(right-left+1)/2; if (arr[mid]>arr[mid-1])left=mid; else right=mid-1; } return; }
标签:二分,arr,right,int,mid,算法,查找,left From: https://www.cnblogs.com/wllovelmbforever/p/17779214.html