首页 > 代码库 > A Product Array Puzzle
A Product Array Puzzle
Given an array arr[] of n integers, construct a Product Array prod[] (of same size) such that prod[i] is equal to the product of all the elements of arr[] except arr[i]. Solve it without division operator and in O(n).
Example:
arr[] = {10, 3, 5, 6, 2}
prod[] = {180, 600, 360, 300, 900}
1 public static int[] selfExcluding(int[] input){ 2 if(input == null || input.length == 0) return null; 3 int len = input.length; 4 int[] output = new int[len]; 5 for(int i = 0; i < len; i ++){ 6 output[i] = 1; 7 } 8 int left = 1, right = 1; 9 for(int i = 1; i < input.length; i ++){10 left *= input[i - 1];11 output[i] *= left; 12 right *= input[len - i];13 output[len - i - 1] *= right;14 }15 return output;16 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。