Advertisement
Guest User

Untitled

a guest
Jan 21st, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. package com.hrishikesh.practices.array;
  2.  
  3. import java.util.Arrays;
  4.  
  5. import static com.hrishikesh.practices.array.ArrayProduct.getProducts;
  6. import static com.hrishikesh.practices.array.ArrayProduct.getProducts2;
  7.  
  8. /**
  9. * Problem
  10. * Product of array elements except self
  11. * Given an array of n integers of array size greater than one,
  12. * return an array result such that result[i] is equal to the product of all the elements except it self index.
  13. * ;
  14. * Constraints:
  15. * - time O(n)
  16. * - And without divide operation
  17. *
  18. * @author hrishikesh.mishra
  19. */
  20. public class ArrayProduct {
  21.  
  22. /**
  23. * In constant memory
  24. *
  25. * @param arrays
  26. * @return
  27. */
  28. public static int[] getProducts2(int[] arrays) {
  29. int n = arrays.length;
  30. int[] result = new int[n];
  31.  
  32. result[0] = 1;
  33.  
  34. /** Left portion **/
  35. for (int i = 1; i < n; i++) {
  36. result[i] = result[i - 1] * arrays[i - 1];
  37. }
  38.  
  39. /** Right portion **/
  40. int right = arrays[n - 1];
  41. for (int j = n - 2; j >= 0; j--) {
  42. result[j] = right * result[j];
  43. right *= arrays[j];
  44. }
  45.  
  46.  
  47. return result;
  48. }
  49.  
  50. public static int[] getProducts(int[] arrays) {
  51. int n = arrays.length;
  52. int[] left = new int[n];
  53. int[] right = new int[n];
  54. int[] result = new int[n];
  55.  
  56. left[0] = 1;
  57. right[n - 1] = 1;
  58.  
  59. /** Left portion **/
  60. for (int i = 1; i < n; i++) {
  61. left[i] = left[i - 1] * arrays[i - 1];
  62. }
  63.  
  64. /** Right portion **/
  65. for (int j = n - 2; j >= 0; j--) {
  66. right[j] = right[j + 1] * arrays[j + 1];
  67. }
  68.  
  69. /** Result **/
  70. for (int i = 0; i < n; i++) {
  71. result[i] = left[i] * right[i];
  72. }
  73.  
  74. return result;
  75. }
  76. }
  77.  
  78. class ArrayProductTest {
  79. public static void main(String[] args) {
  80. int[] array = {9, 0, -2};
  81. System.out.println("Array: " + Arrays.toString(array));
  82. System.out.println("Product: " + Arrays.toString(getProducts(array)));
  83. System.out.println("Product2: " + Arrays.toString(getProducts2(array)));
  84.  
  85. }
  86.  
  87.  
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement