标签:
原题链接在这里:https://leetcode.com/problems/product-of-array-except-self/
看到这道题内心十分憎恨自己,这道题在Amazon电面中遇到,当时没有刷题,没有想到这种方法,若是当时刷了题该多好。
leftArr rightArr的方法早已知晓。follow-up 里说不用额外空间,可以采用res数组间接保留leftArr 和 rightArr 数组.
两遍iteration, 第一遍更新成右侧,第二遍,从左开始依次乘以left.
Note: 该i--时不要顺手写成i++.
AC Java:
1 public class Solution { 2 public int[] productExceptSelf(int[] nums) { 3 /* 4 //Method 1 5 if(nums == null || nums.length == 0){ 6 return null; 7 } 8 int [] leftArr = new int[nums.length]; 9 int [] rightArr = new int[nums.length]; 10 int left = 1; 11 int right =1; 12 13 for(int i = 0; i<nums.length; i++){ 14 leftArr[i] = left; 15 left*=nums[i]; 16 } 17 for(int i = nums.length-1; i>=0; i--){ 18 rightArr[i] = right; 19 right*=nums[i]; 20 } 21 int [] res = new int[nums.length]; 22 for(int i = 0; i< nums.length; i++){ 23 res[i] = leftArr[i] * rightArr[i]; 24 } 25 return res; 26 */ 27 //Method 2 28 if(nums == null || nums.length == 0){ 29 return null; 30 } 31 int [] res = new int[nums.length]; 32 res[nums.length-1] = 1; 33 for(int i = nums.length-2; i>=0; i--){ 34 res[i] = res[i+1] * nums[i+1]; 35 } 36 int left = 1; 37 for(int i = 0; i<nums.length; i++){ 38 res[i] *= left; 39 left *= nums[i]; 40 } 41 return res; 42 } 43 }
LeetCode Product of Array Except Self
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4881249.html