Solving codingBat Post4 with one loop in Java
Solving codingBat Post4 with one loop in Java
- Before iteration create result array, lets say with length 0.
- Each time you find
4
create new result array with size based on index of that4
and length ofnums
to store rest of elements. - If number is not
4
place it in result array (dont place if result arrays length is0
because it means we didnt find any4
yet, or it was last element ofnums
array).
Here is example 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;
}
You may use the class Arrays…that is:
public int[] post4(int[] nums) {
int lastFourIndex = 0;
for (int i = 0; i < nums.length; i++) {
if(nums[i] == 4)
{
lastFourIndex = i;
}
}
return Arrays.copyOfRange(nums, lastFourIndex+1, nums.length);
}
Angelo
Solving codingBat Post4 with one loop in Java
post4 problem solution code:
I have tried this code and its perfectly working. Try this on your IDE.
public int[] m1(int[] nums) {
int c = 0;
for (int i = 0; i < nums.length;) {
if(nums[i]!=4){
i= i+1;
}
else if(nums[i] == 4){
c = i;
i = i+1;
}
}
int count = 0;
for (int i = c+1; i < nums.length; i++) {
if(nums[i]!=4){
count = count+1;
}
else
break;
}
int b[] = new int[count];
int j = 0;
for (int i = c+1; i < nums.length; i++) {
b[j] = nums[i];
j++;
}
return b;
}