Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 51b4a8a

Browse files
Merge branch 'youngyangyang04:master' into master
2 parents a9d679b + 69b5fb5 commit 51b4a8a

File tree

2 files changed

+46
-5
lines changed

2 files changed

+46
-5
lines changed

‎problems/0027.移除元素.md‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -146,18 +146,14 @@ public:
146146
};
147147
```
148148

149-
149+
150150
## 相关题目推荐
151151

152152
* 26.删除排序数组中的重复项
153153
* 283.移动零
154154
* 844.比较含退格的字符串
155155
* 977.有序数组的平方
156156

157-
158-
159-
160-
161157
## 其他语言版本
162158

163159

@@ -177,6 +173,26 @@ class Solution {
177173
}
178174
}
179175
```
176+
```java
177+
//相向双指针法
178+
class Solution {
179+
public int removeElement(int[] nums, int val) {
180+
int left = 0;
181+
int right = nums.length - 1;
182+
while(right >= 0 && nums[right] == val) right--; //将right移到从右数第一个值不为val的位置
183+
while(left <= right) {
184+
if(nums[left] == val) { //left位置的元素需要移除
185+
//将right位置的元素移到left(覆盖),right位置移除
186+
nums[left] = nums[right];
187+
right--;
188+
}
189+
left++;
190+
while(right >= 0 && nums[right] == val) right--;
191+
}
192+
return left;
193+
}
194+
}
195+
```
180196

181197
Python:
182198

‎problems/0035.搜索插入位置.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,32 @@ class Solution {
226226
}
227227
}
228228
```
229+
```java
230+
//第二种二分法:左闭右开
231+
public int searchInsert(int[] nums, int target) {
232+
int left = 0;
233+
int right = nums.length;
234+
while (left < right) { //左闭右开 [left, right)
235+
int middle = left + ((right - left) >> 1);
236+
if (nums[middle] > target) {
237+
right = middle; // target 在左区间,在[left, middle)中
238+
} else if (nums[middle] < target) {
239+
left = middle + 1; // target 在右区间,在 [middle+1, right)中
240+
} else { // nums[middle] == target
241+
return middle; // 数组中找到目标值的情况,直接返回下标
242+
}
243+
}
244+
// 目标值在数组所有元素之前 [0,0)
245+
// 目标值插入数组中的位置 [left, right) ,return right 即可
246+
// 目标值在数组所有元素之后的情况 [left, right),因为是右开区间,所以 return right
247+
return right;
248+
}
249+
```
250+
251+
252+
229253
Golang:
254+
230255
```golang
231256
// 第一种二分法
232257
func searchInsert(nums []int, target int) int {

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /