forked from lemonbashar/java-algo-expert
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMoveToEnd.java
More file actions
44 lines (37 loc) · 1.1 KB
/
MoveToEnd.java
File metadata and controls
44 lines (37 loc) · 1.1 KB
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
34
35
36
37
38
39
40
41
42
43
44
package algoexpert.medium;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/*
PROBLEM:
Given array and elem, move all instances of elem to end without using extra space.
EXAMPLE:
[2,1,2,2,2,3,4,2] -> [1,3,4,2,2,2,2,2] (1,3 & 4 can be in any order)
SOLUTION:
1. using pointers -> time : O(n) | space : O(1)
*/
public class MoveToEnd
{
public static void test()
{
ArrayList<Integer> array = new ArrayList<> (Arrays.asList(2,1,2,2,2,3,4,2));
System.out.println(moveElementToEnd(array, 2));
}
// time : O(n) | space : O(1)
public static List<Integer> moveElementToEnd(List<Integer> array, int toMove)
{
int lastNonElem = array.size() - 1;
int front = 0;
while (front < lastNonElem)
{
while(lastNonElem > front && array.get(lastNonElem) == toMove) { lastNonElem -= 1; }
if (array.get(front) == toMove)
{
array.set(front, array.get(lastNonElem));
array.set(lastNonElem, toMove);
}
front += 1;
}
return array;
}
}