java: add «27. Remove Element»
URL: https://leetcode.com/problems/remove-element/
This commit is contained in:
parent
4c5a83c578
commit
7e297a3605
1 changed files with 32 additions and 0 deletions
32
java/remove-element.java
Normal file
32
java/remove-element.java
Normal file
|
@ -0,0 +1,32 @@
|
|||
class Solution {
|
||||
private static int skipVal(int[] nums, int val, int i) {
|
||||
for (
|
||||
/* no-op */ ; i >= 0 && nums[i] == val; /* no-op */ ) {
|
||||
--i;
|
||||
}
|
||||
|
||||
return i;
|
||||
}
|
||||
|
||||
public int removeElement(int[] nums, int val) {
|
||||
var r = skipVal(nums, val, nums.length - 1);
|
||||
|
||||
int l;
|
||||
for (l = 0; l < r; ++l) {
|
||||
if (nums[l] == val) {
|
||||
var tmp = nums[l];
|
||||
nums[l] = nums[r];
|
||||
nums[r] = tmp;
|
||||
|
||||
r = skipVal(nums, val, r);
|
||||
}
|
||||
}
|
||||
|
||||
// shift ‹l› to the first ‹val›
|
||||
while (l < nums.length && nums[l] != val) {
|
||||
++l;
|
||||
}
|
||||
|
||||
return l;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue