Skip to content

Commit 3b62ab0

Browse files
remove element
1 parent c8fe046 commit 3b62ab0

File tree

1 file changed

+52
-15
lines changed

1 file changed

+52
-15
lines changed

EASY/src/easy/RemoveElement.java

+52-15
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
package easy;
22

3-
import utils.CommonUtils;
4-
53
/**27. Remove Element
64
75
Total Accepted: 135216
@@ -19,23 +17,62 @@
1917
2018
Your function should return length = 2, with the first two elements of nums being 2.*/
2119
public class RemoveElement {
20+
//then I looked at the Editorial solution, really neat!!! Super elegant and smart!
21+
public int removeElement_editorial_solution_1(int[] nums, int val){
22+
//use two pointers, increment j as long as its not equal to val, return i in the end
23+
int i = 0;
24+
for(int j = 0; j < nums.length; j++){
25+
if(nums[j] != val) nums[i++] = nums[j];
26+
}
27+
return i;
28+
}
29+
30+
public int removeElement_editorial_solution_2(int[] nums, int val){
31+
//this approach is very similar to the one below that I came up totally by myself, but it's much concise
32+
//Here, it didn't check whether nums[n-1] will be equal to val, because in the next iteration, it will still check that number, smart!
33+
int i = 0, n = nums.length;
34+
while(i < n){
35+
if(nums[i] == val){
36+
nums[i] = nums[n-1];
37+
n--;
38+
} else {
39+
i++;
40+
}
41+
}
42+
return i;
43+
}
44+
45+
//just throw all numbers that are equal to val to the end and make a count of it
2246
public int removeElement(int[] nums, int val) {
23-
for(int i = 0; i < nums.length; i++){
24-
int start = i;
25-
while(i < nums.length && nums[i] == val){
26-
i++;
27-
}
28-
if(i == nums.length) i--;
29-
nums[start] = nums[i];
30-
}
31-
CommonUtils.printArray(nums);
32-
return 0;
47+
int count = 0;
48+
int len = nums.length, throwPosition = len-1;
49+
for(int i = 0; i <= throwPosition; i++){
50+
while(throwPosition >= 0 && nums[throwPosition] == val) {
51+
throwPosition--;
52+
count++;
53+
}
54+
if(throwPosition == -1 || i >= throwPosition) break;
55+
if(nums[i] == val){
56+
count++;
57+
int temp = nums[throwPosition];
58+
nums[throwPosition] = nums[i];
59+
nums[i] = temp;
60+
throwPosition--;
61+
}
62+
}
63+
return len-count;
3364
}
3465

3566
public static void main(String...strings){
3667
RemoveElement test = new RemoveElement();
37-
int[] nums = new int[]{3,2,2,3};
38-
int val = 3;
39-
test.removeElement(nums, val);
68+
// int[] nums = new int[]{3,2,2,3};
69+
// int val = 3;
70+
71+
int[] nums = new int[]{2,2,3};
72+
int val = 2;
73+
74+
// int[] nums = new int[]{1};
75+
// int val = 1;
76+
System.out.println(test.removeElement(nums, val));
4077
}
4178
}

0 commit comments

Comments
 (0)