From 57aa0a6aa9538fe37c8595feae037222a22752e1 Mon Sep 17 00:00:00 2001 From: whai Date: Wed, 6 Dec 2023 21:46:19 +0800 Subject: [PATCH] =?UTF-8?q?LeetCode35=E4=BA=8C=E5=88=86=E6=9F=A5=E6=89=BE?= =?UTF-8?q?=20int=20mid=20=3D=20((right=20-=20left)=20>>=201)=20+=20left;?= =?UTF-8?q?=20/2=20=E7=94=A8=E8=BF=99=E4=B8=AA=E6=96=B9=E6=B3=95=20right-l?= =?UTF-8?q?eft=20=E5=B0=B1=E6=98=AF=E4=BB=8E0=E5=BC=80=E5=A7=8B=E5=88=B0n?= =?UTF-8?q?=EF=BC=8C=20=E5=8F=B3=E7=A7=BB=E5=8A=A8=E4=B8=80=E4=BD=8D?= =?UTF-8?q?=E5=B0=B1=E6=98=AF=E9=99=A4=E4=BB=A52=EF=BC=8C=E8=8E=B7?= =?UTF-8?q?=E5=BE=97=E5=88=B0=E8=BF=99=E4=B8=AA=E5=8C=BA=E9=97=B4=E7=9A=84?= =?UTF-8?q?=E4=B8=80=E5=8D=8A=EF=BC=8C=E5=8A=A0=E4=B8=8A=E8=B5=B7=E5=A7=8B?= =?UTF-8?q?=E7=9A=84left=20=E5=B0=B1=E6=98=AF(right=20+=20left)/2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/cn/whaifree/leetCode/easy/LeetCode35.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/cn/whaifree/leetCode/easy/LeetCode35.java b/src/main/java/cn/whaifree/leetCode/easy/LeetCode35.java index bd433d3..14566ee 100644 --- a/src/main/java/cn/whaifree/leetCode/easy/LeetCode35.java +++ b/src/main/java/cn/whaifree/leetCode/easy/LeetCode35.java @@ -44,7 +44,8 @@ public class LeetCode35 { int right = nums.length - 1; // 当左指针小于等于右指针时,进行循环 while (left <= right) { - // 计算中间位置的索引 + // 计算中间位置的索引 右边距减去左边距,右移一位,然后加上左边距,得到中间值 + // right-left 就是从0开始到n, 右移动一位就是除以2,获得到这个区间的一半,加上起始的left 就是(right + left)/2 int middle = ((right - left) >> 1) + left; // 如果中间位置的元素等于目标元素,返回中间位置的索引 if (nums[middle] == target) { @@ -84,6 +85,9 @@ public class LeetCode35 { int[] ints = {1, 3, 5, 8,10}; int[] ints1 = {}; + int middle = ((8 - 4) >> 1) + 4; + + // 1000 - 0100 = 0100 >> 1 = 0010 ==> 2 + 4 System.out.println(searchInsert1(ints, 2)); } }