# java – Code to replace the list of integers by the largest element nearest

The initial question was in the context of a table, but I just used a list without changing the length to make debugging easier. `toString ()`.

Given a list of unsorted integers, design an O (n) algorithm to transform the list so that the integers are replaced by the largest integer immediately to the right. If there is no larger integer on the right, the whole number remains the same. For example, [2,1,4,5,3,6,7,9,4,8] becomes [4,4,5,6,6,7,9,9,8,8].

I came out with an algorithm but I'm not really sure that it's considered O (n) and where I can improve if it's really O (n). Can any one give me feedback?

``````import java.util. *;

Main class {
public static void main (String [] args) {
ArrayList lst = new ArrayList <> (List.degree (2,1,4,5,3,6,7,9,4,8));
replace2 (lst);
System.out.println (lst);
}

// O (n ^ 2) algorithm
empty static public replace (int [] arr) {
for (int i = 0; i <arr.length; i ++) {
for (int j = i; j <arr.length; j ++) {
if (arr[i]<arr[j]) {
arr[i]= arr[j];
Pause;
}
}
}
}

// O (n) algorithm
empty static public replace2 (ArrayList lst) {
int index = 0;
int vu = 0;
for (int i = 0; i< lst.size()-1;i++) {
boolean isBroken = false;
if (lst.get(i) >= lst.get (i + 1)) {// if the adjacent element is larger, look for the next largest
for (int j = i; j < lst.size(); j++) {
if (lst.get(j) > lst.get (i)) {
index = j;
vu = lst.get (j);
isBroken = true;
Pause;
}
}
if (isBroken) {// if we found the next bigger one
for (int k = index-1; k> i-1; k--) {
if (lst.get (k) <vu) {
if (lst.get (k) <lst.get (i)) {
lst.set (k, vu);
} other {
int temp = lst.get (k);
lst.set (k, vu);
vu = temp;
}
}
}
}

} else {// the adjacent element is already bigger
lst.set (i, lst.get (i + 1));
}
}
}
}
``````

Posted on