Pregunta de entrevista
Entrevista de Technical Account Manager
-
Google* Given an array of numbers. Create another array that contains * the product of all the members in the array except the current * element. For example, if you have an array of 3 elements such as: * * A[0] = 2 * A[1] = 4 * A[2] = 6 * * Then the resulting array will be * B[0] = 24 * B[1] = 12 * B[2] = 8 *
Respuestas de entrevistas
10 respuestas
public class GoogleInterviewQuestion { public int[] computeProds(int[] intArray) { int product = 1; int[] prods = new int[intArray.length]; for (int i = 0; i < intArray.length; i++) { product *= intArray[i]; } for (int i = 0; i < intArray.length; i++) { prods[i] = product / intArray[i]; } return prods; } public static void main (int argc, String argv[]) { GoogleInterviewQuestion giq = new GoogleInterviewQuestion(); int array[] = {2, 4, 6, 8, 10}; int prods[] = giq.computeProds(array); }
Anónimo en
More than division by 0, it will fail if any element of original array is 0. All elements of resultant array will be 0? While one element dosent need to be 0.
annonymous en
Or even better: def ComputeProds(arr): return [reduce(lambda x,y: x*y, set(arr).difference([c])) for c in arr]
Mr Pythonic en
public class Main{ public static void main(String[] args){ //every cell holds multi of int[] input = {1,2,1,4,4,5}; int times_zero = 0 ;//if 1, all are zero but that one, if above, all are zero int[] ans = new int[input.length]; int prod_wo_zero = 1; int i; for(i=0;i
FatalException en
public static void run(){ List nums = Arrays.asList(5,1,2,3); List result = new ArrayList(); int partial = 1; for (int i = 0; i< nums.size();i++){ for (int j = 0; j< nums.size();j++){ if (j != i){ partial = partial * nums.get(j); } } result.add(partial); partial = 1; } for (int num : result) System.out.println(num); }
Anónimo en
Here is the best answer: int product = 1; for(int i=0;i< A.length;i++){ product *= A[i]; } for(int i=0;i< A.length;i++){ B[i] = product/A[i]; }
Amin Dulkumoni en
Watch out for division by 0! Just multiply by 1 or skip over.
anonymous en
def m(arr): new_arr = [] for current in arr: diff = set(arr).difference([current]) r = reduce(lambda x,y: x*y, diff) new_arr.append(r) return new_arr
Mr Pythonic en
1. Cases are - no cell is zero, only one cell is zero - results in all zeros but that, more than one is zero - results in all zeros public class Main{ public static void main(String[] args){ //every cell holds multi of int[] input = {1,2,1,4,0,5}; int times_zero = 0 ;//if 1, all are zero but that one, if above, all are zero int[] ans = new int[input.length]; int prod_with_zero,prod_wo_zero = 1; int i; for(i=0;i
FatalException en
public class ArrayOperations { public static void main(String[] args){ ArrayOperations test = new ArrayOperations(); int[] values = {12, 4, 9, 16, 20, 5, 1 }; values = test.multiplyExclusive(values); for(int i=0; i
Ikenna en