A
A
Algorithm Practice
Search…
A
A
Algorithm Practice
Introduction
Lintcode
Leetcode
Math
Tree
Graph
Two Pointers
3 Longest Substring Without Repeating Characters
11 Container With Most Water
15 3Sum
16 3Sum Closest
18 4Sum
26 Remove Duplicates from Sorted Array
27 Remove Element
30 Substring with Concatenation of All Words
42 Trapping Rain Water
76 Minimum Window Substring
80 Remove Duplicates from Sorted Array II
88 Merge Sorted Array
125 Valid Palindrome
159 Longest Substring with At Most Two Distinct Characters
167 Two Sum II - Input array is sorted
202 Happy Number
209 Minimum Size Subarray Sum
259 3Sum Smaller
283 Move Zeroes
340 Longest Substring with At Most K Distinct Characters
344 Reverse String
345 Reverse Vowels of a String
349 Intersection of Two Arrays
350 Intersection of Two Arrays II
360 Sort Transformed Array
395 Longest Substring with At Least K Repeating Characters
424 Longest Repeating Character Replacement
438 Find All Anagrams in a String
487 Max Consecutive Ones II
524 Longest Word in Dictionary through Deleting
532 K-diff Pairs in an Array
567 Permutation in String
611 Valid Triangle Number
632 Smallest Range
713 Subarray Product Less Than K
723 Candy Crush
763 Partition Labels
Linked List
Topological Sort
Hash Table
Trie
Sort
Binary Search
Heap
Breadth First Search
Stack
Backtracking
Dynamic Programming
Union Find
Scan Line
String
Reservoir Sampling
Recursion
Google
Powered By
GitBook
27 Remove Element
27. Remove Element
1. Question
Given an array and a value, remove all instances of that value
in-place
and return the new length.
Do not allocate extra space for another array, you must do this by
modifying the input array
in-place
with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
1
Given nums = [3,2,2,3], val = 3,
2
3
Your function should return length = 2, with the first two elements of nums being 2.
Copied!
2. Implementation
1
public
class
Solution
{
2
public
int
removeElement
(
int
[]
nums
,
int
val
)
{
3
if
(
nums
==
null
||
nums
.
length
==
0
)
{
4
return
0
;
5
}
6
7
int
index
=
0
;
8
for
(
int
num
:
nums
)
{
9
if
(
num
!=
val
)
{
10
nums
[
index
++
]
=
num
;
11
}
12
}
13
return
index
;
14
}
15
}
Copied!
3. Time & Space Complexity
时间复杂度O(n), 空间复杂度O(1)
Previous
26 Remove Duplicates from Sorted Array
Next
30 Substring with Concatenation of All Words
Last modified
2yr ago
Copy link
Contents
27. Remove Element
1. Question
2. Implementation
3. Time & Space Complexity