From 90b60a600542c17f28b491f4640ff615f654eb01 Mon Sep 17 00:00:00 2001 From: wzs <1014355013@qq.com> Date: Wed, 12 May 2021 14:53:46 +0800 Subject: [PATCH 1/2] =?UTF-8?q?0035.=E6=90=9C=E7=B4=A2=E6=8F=92=E5=85=A5?= =?UTF-8?q?=E4=BD=8D=E7=BD=AE=E5=92=8CJava=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0035.搜索插入位置.md | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md index 5bd3b553..12fe714e 100644 --- a/problems/0035.搜索插入位置.md +++ b/problems/0035.搜索插入位置.md @@ -205,9 +205,36 @@ public: ## 其他语言版本 - Java: +```java +class Solution { + public int searchInsert(int[] nums, int target) { + int n = nums.length; + + // 定义target在左闭右闭的区间里,[low, high] + int low = 0; + int high = n - 1; + + while (low <= high) { // 当low==high,区间[low, high]依然有效 + int mid = low + (high - low) / 2; // 防止溢出 + if (nums[mid] > target) { + high = mid - 1; // target 在左区间,所以[low, mid - 1] + } else if (nums[mid] < target) { + low = mid + 1; // target 在右区间,所以[mid + 1, high] + } else { + // 1. 目标值等于数组中某一个元素 return mid; + return mid; + } + } + // 2.目标值在数组所有元素之前 3.目标值插入数组中 4.目标值在数组所有元素之后 return right + 1; + return high + 1; + } +} +``` + + + Python: From 8cdefe9f92362f71a1beffa46ff805ae2a95a4fb Mon Sep 17 00:00:00 2001 From: wzs <1014355013@qq.com> Date: Wed, 12 May 2021 14:56:48 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A00035.=E6=90=9C=E7=B4=A2?= =?UTF-8?q?=E6=8F=92=E5=85=A5=E4=BD=8D=E7=BD=AE=E5=92=8CJava=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0035.搜索插入位置.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md index 12fe714e..c351e365 100644 --- a/problems/0035.搜索插入位置.md +++ b/problems/0035.搜索插入位置.md @@ -212,7 +212,7 @@ class Solution { public int searchInsert(int[] nums, int target) { int n = nums.length; - // 定义target在左闭右闭的区间里,[low, high] + // 定义target在左闭右闭的区间,[low, high] int low = 0; int high = n - 1;