Bloomberg LP Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
The simple way is get a temporary index which is initial with 0; Look at code
// temporary index;
index = 0;
// go over array
for (number in numbers) {
if (number % 2 == 0) { // if number is even
// you just say, for current index put me this number, which is not odd
numbers[index++] = number;
}
}
// the last tricky is update your length with index;
numbers.resize(index)
That's all
import java.util.*;
public class Solution{
public static void main(String[] args){
List<Integer> nums = new ArrayList<Integer>();
nums.add(1);
nums.add(2);
nums.add(3);
nums.add(4);
nums.add(5);
nums.add(-6);
nums.add(7);
nums.add(8);
nums.add(9);
nums.add(10);
deleteNum(nums);
}
public static void deleteNum(List<Integer> nums){
for(int i=0;i<nums.size();i++){
if(nums.get(i)%2 != 0){
nums.remove(i);
}
}
for(Integer s: nums){
System.out.println(s);
}
}
}
import java.util.*;
public class Solution{
public static void main(String[] args){
List<Integer> nums = new ArrayList<Integer>();
nums.add(1);
nums.add(2);
nums.add(3);
nums.add(4);
nums.add(5);
nums.add(-6);
nums.add(7);
nums.add(8);
nums.add(9);
nums.add(10);
deleteNum(nums);
}
public static void deleteNum(List<Integer> nums){
for(int i=0;i<nums.size();i++){
if(nums.get(i)%2 != 0){
nums.remove(i);
}
}
for(Integer s: nums){
System.out.println(s);
}
}
}
Joe's refactored variant:
public static void main(String[] args) {
List<Integer> nums = new ArrayList<Integer>();
nums.add(1);
nums.add(1);
nums.add(1);
nums.add(1);
nums.add(1);
nums.add(1);
nums.add(1);
nums.add(1);
nums.add(1);
nums.add(10);
deleteNum(nums);
}
public static void deleteNum(List<Integer> nums) {
int index = 0;
int count = nums.size();
while (count > 0) {
if (nums.get(index) % 2 != 0) {
nums.remove(index);
} else {
System.out.println(nums.get(index));
index++;
}
count--;
}
}
- Alex September 08, 2017