Skip to content

Commit 8e2001e

Browse files
committed
27 Remove Element
1 parent ce4ee78 commit 8e2001e

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
+ [21 Merge Two Sorted Lists](algorithms/MergeTwoSortedLists)
1818
+ [22 Generate Parentheses(递归、搜索)](algorithms/GenerateParentheses)
1919
+ [26 Remove Duplicates from Sorted Array](algorithms/RemoveDuplicatesfromSortedArray)
20+
+ [27 Remove Element](algorithms/RemoveElement)
2021
+ [29 Divide Two Integers(位运算、最小负数绝对值、溢出检测)](algorithms/DivideTwoIntegers)
2122
+ [31 Next Permutation(全排列)](algorithms/NextPermutation)
2223
+ [35 Search Insert Position(二分查找)](algorithms/SearchInsertPosition)

algorithms/RemoveElement/README.md

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
## Remove Element
2+
3+
Given an array and a value, remove all instances of that value in place and return the new length.
4+
5+
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
6+
7+
## Solution
8+
遍历数组,并逐一原地拷贝不等于key的元素
9+
```cpp
10+
int removeElement(int a[], int n, int key)
11+
{
12+
int k = 0;
13+
for (int i = 0; i < n; ++i) {
14+
if (a[i] != key)
15+
a[k++] = a[i];
16+
}
17+
return k;
18+
}
19+
```

algorithms/RemoveElement/solve.c

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <string.h>
4+
int removeElement(int a[], int n, int key)
5+
{
6+
int k = 0;
7+
for (int i = 0; i < n; ++i) {
8+
if (a[i] != key)
9+
a[k++] = a[i];
10+
}
11+
return k;
12+
}
13+
int main(int argc, char **argv)
14+
{
15+
int a[] = {1,2,3,2,3,2,1,6,2};
16+
int n = removeElement(a, 9, 2);
17+
for (int i = 0; i < n; ++i)
18+
printf("%d ", a[i]);
19+
printf("\n");
20+
return 0;
21+
}

0 commit comments

Comments
 (0)