Guest User

Untitled

a guest
Jun 20th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. */
  2. Given an array nums of n integers where n > 1,
  3. return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
  4.  
  5. Example:
  6.  
  7. Input: [1,2,3,4]
  8. Output: [24,12,8,6]
  9. Note: Please solve it without division and in O(n).
  10. */
  11.  
  12. class Solution {
  13. public int[] productExceptSelf(int[] nums) {
  14. if (nums.length < 2) {
  15. throw new IllegalArgumentException("Array must have more than 2 numbers to compute product");
  16. }
  17. int[] productsBeforeIndex = getProductsBeforeIndex(nums);
  18. int[] productsAfterIndex = reverseArray(getProductsBeforeIndex(reverseArray(nums)));
  19.  
  20. return productsOfTwoArrays(productsBeforeIndex, productsAfterIndex);
  21. }
  22.  
  23. public int[] getProductsBeforeIndex(int[] a) {
  24. int[] res = new int[a.length];
  25. res[0] = 1;
  26. for (int i = 1; i < a.length; i++) {
  27. res[i] = res[i - 1] * a[i - 1];
  28. }
  29. return res;
  30. }
  31.  
  32. public int[] reverseArray(int[] a) {
  33. for (int i = 0; i < a.length / 2; i++) {
  34. int temp = a[i];
  35. a[i] = a[a.length - 1 - i];
  36. a[a.length - 1 - i] = temp;
  37. }
  38. return a;
  39. }
  40.  
  41. public int[] productsOfTwoArrays(int[] a1, int[] a2) {
  42. int[] res = new int[a1.length];
  43. for (int i = 0; i < a1.length; i++) {
  44. res[i] = a1[i] * a2[i];
  45. }
  46. return res;
  47. }
  48. }
Add Comment
Please, Sign In to add comment