Java > Array-2 > Coding Bat Problem Given a non-empty array of ints, return a ne
ID: 3761739 • Letter: J
Question
Java > Array-2 > Coding Bat Problem
Given a non-empty array of ints, return a new array containing the elements from the original array that come after the last 4 in the original array. The original array will contain at least one 4. Note that it is valid in java to create an array of length 0.
post4({2, 4, 1, 2}) {1, 2}
post4({4, 1, 4, 2}) {2}
post4({4, 4, 1, 2, 3}) {1, 2, 3}
People on the Internet supposedly are worried about complexity. They say that in order to get a better complexity, there should not be two loops.
So here is the solution that they are not happy with:
public int[] post4(int[] nums) {
int count = 0;
for (int i = nums.length - 1; i >= 0; i--) {
if (nums[i] == 4) {
count = i;
break;
}
}
int[] result = new int[nums.length - (count + 1)];
for (int i = count + 1, j = 0; i < nums.length; i++, j++) {
result[j] = nums[i];
}
return result;
}
and here is the "neat" solution:
public int[] post4(int[] nums) {
int[] result = new int[0];
int j = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 4) {
result = new int[nums.length - i - 1];
j = 0;
} else if (result.length > 0) result[j++] = nums[i];
}
return result;
}
Please comment on the complexities of the two in the form of Big(O) Notation. Are the people of the web neccessarily correct in saying the first solution is inappropriately implemented because of a supposed higher complexity? Or is the the second, "neat" solution more correct because of a supposed lower complexity and removal of the extra loop?