-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_0027.java
More file actions
33 lines (31 loc) · 990 Bytes
/
_0027.java
File metadata and controls
33 lines (31 loc) · 990 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.github.aditya;
public class _0027 {
// 0ms, faster than 100%
// Two Pointers - i in front and j at the tail of error
// When i encounters val and j doesn't swap
class Solution {
public int removeElement(int[] nums, int val) {
int i = 0, j = nums.length - 1;
while (i < j) {
if (nums[i] != val && nums[j] != val) {
i++;
} else if (nums[i] == val && nums[j] != val) {
swap(nums, i, j);
i++;
j--;
} else if (nums[i] != val && nums[j] == val) {
i++;
j--;
} else if (nums[i] == val && nums[j] == val) {
j--;
}
}
return i;
}
public void swap(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}
}