Skip to content

Commit 13ab1f6

Browse files
committed
RemoveElement Leetcode
1 parent 8eae640 commit 13ab1f6

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

Diff for: Code/src/RemoveElement.java

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*27. Remove Element
2+
Solved
3+
Easy
4+
Topics
5+
Companies
6+
Hint
7+
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
8+
9+
Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
10+
11+
Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
12+
Return k.
13+
Custom Judge:
14+
15+
The judge will test your solution with the following code:
16+
17+
int[] nums = [...]; // Input array
18+
int val = ...; // Value to remove
19+
int[] expectedNums = [...]; // The expected answer with correct length.
20+
// It is sorted with no values equaling val.
21+
22+
int k = removeElement(nums, val); // Calls your implementation
23+
24+
assert k == expectedNums.length;
25+
sort(nums, 0, k); // Sort the first k elements of nums
26+
for (int i = 0; i < actualLength; i++) {
27+
assert nums[i] == expectedNums[i];
28+
}
29+
If all assertions pass, then your solution will be accepted.
30+
31+
32+
33+
Example 1:
34+
35+
Input: nums = [3,2,2,3], val = 3
36+
Output: 2, nums = [2,2,_,_]
37+
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
38+
It does not matter what you leave beyond the returned k (hence they are underscores).
39+
Example 2:
40+
41+
Input: nums = [0,1,2,2,3,0,4,2], val = 2
42+
Output: 5, nums = [0,1,4,0,3,_,_,_]
43+
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
44+
Note that the five elements can be returned in any order.
45+
It does not matter what you leave beyond the returned k (hence they are underscores).
46+
47+
48+
Constraints:
49+
50+
0 <= nums.length <= 100
51+
0 <= nums[i] <= 50
52+
0 <= val <= 100 */
53+
54+
import java.util.Arrays;
55+
56+
class RemoveElement {
57+
public static int removeElement(int[] nums, int val) {
58+
int k = 0;
59+
for(int i=0;i<nums.length;i++)
60+
{
61+
if(nums[i]!=val)
62+
{
63+
nums[k]=nums[i];
64+
k++;
65+
}
66+
67+
}
68+
return k;
69+
}
70+
public static void main (String[] args)
71+
{
72+
int[] arr={3,2,2,3,4,3,5,5,6,7,8,23,50,3,1,2,3,43,3,43,3,3};
73+
int r = removeElement(arr,3);
74+
Arrays.stream(arr,0,r).boxed().forEach(a->System.out.print(a+" "));
75+
System.out.println();
76+
System.out.println(r);
77+
}
78+
}

0 commit comments

Comments
 (0)