algorithm-base/animation-simulation/数组篇/leetcode27移除元素.md

186 lines
6.0 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [27. ](https://leetcode-cn.com/problems/remove-element/)
****
> nums val val
>
> 使使 O(1)
>
>
** 1:**
> nums = [3,2,2,3], val = 3,
>
> 2, nums 2
>
>
** 2:**
> nums = [0,1,2,2,3,0,4,2], val = 2,
>
> 5, nums 0, 1, 3, 0, 4
>
>
>
>
****
****
102 8 8 for
![](https://cdn.jsdelivr.net/gh/tan45du/github.io.phonto2@master/myphoto/移除数组元素.lhuefelqd5o.png)
1len nums.length
2i--
****
Java Code:
```java
class Solution {
public int removeElement(int[] nums, int val) {
//获取数组长度
int len = nums.length;
if (len == 0) {
return 0;
}
int i = 0;
for (i = 0; i < len; ++i) {
//发现符合条件的情况
if (nums[i] == val) {
//前移一位
for (int j = i; j < len-1; ++j) {
nums[j] = nums[j+1];
}
i--;
len--;
}
}
return i;
}
}
```
Python3 Code:
```python
from typing import List
class Solution:
def removeElement(self, nums: List[int], val: int)->int:
#
leng = len(nums)
if 0 == leng:
return 0
i = 0
while i < leng:
#
if nums[i] == val:
#
for j in range(i, leng - 1):
nums[j] = nums[j + 1]
i -= 1
leng -= 1
i += 1
return i
```
****
for O(n) ,
**:**
![](https://img-blog.csdnimg.cn/20210317194638700.gif#pic_center)
****
Java Code:
```java
class Solution {
public int removeElement(int[] nums, int val) {
int len = nums.length;
if (len == 0) {
return 0;
}
int i = 0;
for (int j = 0; j < len; ++j) {
//如果等于目标值,则删除
if (nums[j] == val) {
continue;
}
// 不等于目标值时则赋值给nums[i],i++
nums[i++] = nums[j];
}
return i;
}
}
```
Python3 Code:
```python
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
i = 0
for j in range(len(nums)):
if nums[j] != val:
nums[i] = nums[j]
i += 1
return i
```
C++ Code:
```cpp
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int n = nums.size();
if(!n) return 0;
int i = 0;
for(int j = 0; j < n; ++j){
if(nums[j] == val) continue;
nums[i++] = nums[j];
}
return i;
}
};
```
Swift Code
```swift
class Solution {
func removeElement(_ nums: inout [Int], _ val: Int) -> Int {
if nums.count == 0 {
return 0
}
var i = 0
for j in 0..<nums.count {
if nums[j] != val {
nums[i] = nums[j]
i += 1
}
}
return i
}
}
```