Last active
June 20, 2018 14:18
-
-
Save uday-rayala/43b4792c6d40120f388c54552c53b069 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
class Solution { | |
public int[] products(int[] nums) { | |
int[] result = new int[nums.length]; | |
if (nums.length > 1) { | |
result[0] = 1; | |
} | |
int productSoFar = nums[0]; | |
for (int i = 1; i < nums.length; i++) { | |
result[i] = productSoFar; | |
productSoFar = productSoFar * nums[i]; | |
} | |
productSoFar = nums[nums.length - 1]; | |
for (int i = nums.length - 2; i >= 0; i--) { | |
result[i] = result[i] * productSoFar; | |
productSoFar = productSoFar * nums[i]; | |
} | |
return result; | |
} | |
public static void main(String[] args) { | |
System.out.println(Arrays.toString(new Solution().products(new int[]{1, 2, 3, 4, 5}))); | |
System.out.println(Arrays.toString(new Solution().products(new int[]{1}))); | |
System.out.println(Arrays.toString(new Solution().products(new int[]{10, 20, 0, 30, 40}))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment