mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加0027.移除元素 相向双指针法Java版本
This commit is contained in:
@ -154,10 +154,6 @@ public:
|
|||||||
* 844.比较含退格的字符串
|
* 844.比较含退格的字符串
|
||||||
* 977.有序数组的平方
|
* 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:
|
Python:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user