Merge pull request #1589 from YunChenCloud/master

添加 0035.搜索插入位置 第二种二分法、0027.移除元素 相向双指针法 Java版本
This commit is contained in:
程序员Carl
2022-08-24 10:01:15 +08:00
committed by GitHub
2 changed files with 46 additions and 5 deletions

View File

@ -154,10 +154,6 @@ public:
* 844.比较含退格的字符串
* 977.有序数组的平方
## 其他语言版本
@ -177,6 +173,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

View File

@ -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 {