From 300b8f9f3e5e0233947cb08d97ea67f4840fceb3 Mon Sep 17 00:00:00 2001 From: Yuki Chen <826992207@qq.com> Date: Thu, 18 Aug 2022 10:52:42 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200035.=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=8F=92=E5=85=A5=E4=BD=8D=E7=BD=AE=20=E7=AC=AC?= =?UTF-8?q?=E4=BA=8C=E7=A7=8D=E4=BA=8C=E5=88=86=E6=B3=95Java=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 | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/problems/0035.搜索插入位置.md b/problems/0035.搜索插入位置.md index f2bbb8ca..5ed3ac56 100644 --- a/problems/0035.搜索插入位置.md +++ b/problems/0035.搜索插入位置.md @@ -226,7 +226,32 @@ class Solution { } } ``` +```java +//第二种二分法:左闭右开 +public int searchInsert(int[] nums, int target) { + int left = 0; + int right = nums.length; + while (left < right) { //左闭右开 [left, right) + int middle = left + ((right - left) >> 1); + if (nums[middle] > target) { + right = middle; // target 在左区间,在[left, middle)中 + } else if (nums[middle] < target) { + left = middle + 1; // target 在右区间,在 [middle+1, right)中 + } else { // nums[middle] == target + return middle; // 数组中找到目标值的情况,直接返回下标 + } + } + // 目标值在数组所有元素之前 [0,0) + // 目标值插入数组中的位置 [left, right) ,return right 即可 + // 目标值在数组所有元素之后的情况 [left, right),因为是右开区间,所以 return right + return right; +} +``` + + + Golang: + ```golang // 第一种二分法 func searchInsert(nums []int, target int) int { From d53246138d67e2054b54bd30b596cc4e427ee25a Mon Sep 17 00:00:00 2001 From: Yuki Chen <826992207@qq.com> Date: Sat, 20 Aug 2022 11:54:39 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A00027.=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E5=85=83=E7=B4=A0=20=E7=9B=B8=E5=90=91=E5=8F=8C=E6=8C=87?= =?UTF-8?q?=E9=92=88=E6=B3=95Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0027.移除元素.md | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/problems/0027.移除元素.md b/problems/0027.移除元素.md index 12f88c75..68b1d4bd 100644 --- a/problems/0027.移除元素.md +++ b/problems/0027.移除元素.md @@ -146,7 +146,7 @@ public: }; ``` - + ## 相关题目推荐 * 26.删除排序数组中的重复项 @@ -154,10 +154,6 @@ public: * 844.比较含退格的字符串 * 977.有序数组的平方 - - - - ## 其他语言版本 @@ -180,6 +176,26 @@ class Solution { } } ``` +```java +//相向双指针法 +class Solution { + public int removeElement(int[] nums, int val) { + int left = 0; + int right = nums.length - 1; + while(right >= 0 && nums[right] == val) right--; //将right移到从右数第一个值不为val的位置 + while(left <= right) { + if(nums[left] == val) { //left位置的元素需要移除 + //将right位置的元素移到left(覆盖),right位置移除 + nums[left] = nums[right]; + right--; + } + left++; + while(right >= 0 && nums[right] == val) right--; + } + return left; + } +} +``` Python: