LeetCode Product of Array Except Self
2015-07-20 19:03
323 查看
Given an array of n integers where n > 1,
return an array
equal to the product of all the elements of
Solve it without division and in O(n).
For example, given
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
题意:给出一个数组,求数组中除去其中一个数的乘积
思路:用left[i]表示i左边数的乘积,right[i]表示i右边数的乘积,则output[i] = left[i] *right[i],可以进一步优化,先用output[i]计算出left[i]
代码如下
public class Solution
{
public int[] productExceptSelf(int[] nums)
{
int len = nums.length;
int[] ans = new int[len];
for (int i = 0, tmp = 1; i < len; i++)
{
ans[i] = tmp;
tmp *= nums[i];
}
for (int i = len - 1, tmp = 1; i >= 0; i--)
{
ans[i] *= tmp;
tmp *= nums[i];
}
return ans;
}
}
nums,
return an array
outputsuch that
output[i]is
equal to the product of all the elements of
numsexcept
nums[i].
Solve it without division and in O(n).
For example, given
[1,2,3,4], return
[24,12,8,6].
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
题意:给出一个数组,求数组中除去其中一个数的乘积
思路:用left[i]表示i左边数的乘积,right[i]表示i右边数的乘积,则output[i] = left[i] *right[i],可以进一步优化,先用output[i]计算出left[i]
代码如下
public class Solution
{
public int[] productExceptSelf(int[] nums)
{
int len = nums.length;
int[] ans = new int[len];
for (int i = 0, tmp = 1; i < len; i++)
{
ans[i] = tmp;
tmp *= nums[i];
}
for (int i = len - 1, tmp = 1; i >= 0; i--)
{
ans[i] *= tmp;
tmp *= nums[i];
}
return ans;
}
}
相关文章推荐
- 欢迎使用CSDN-markdown编辑器
- Qt学习之一,键盘事件细节
- shell内部命令和外部命令
- 1336 - Fixing the Great Wall(DP)
- Android应用开发之(WebView中loadData与loadDataWithBaseURL的使用上的区别)
- 使用中国网建实现Java向手机发送短信的功能
- 初学structs2,结果类型简单示例
- Linux Kernel API man (ubuntu)
- HDU 4279 Number 坑爹的迷之精度
- 设置触摸代理的方法
- hdoj-1086-You can Solve a Geometry Problem too 判断线段是否相交
- SlideMenu+Fragment+FragmentTabHost
- 自定义数据类型的序列化
- Android切换页面效果的实现二:WebView+ViewPager
- 【攻克Android (3)】资源国际化、屏幕适配
- Watch OS 2 中 Taptic Engine 的开发教程
- 去掉matlab中figure图的空白边缘
- 【linux】ubuntu14.04安装eclipse4.5
- 自定义EditText,自带清除内容按钮
- 分治(归并排序)