劍指Offer-52

題目:

給定一個數組A[0,1,…,n-1],請構建一個數組B[0,1,…,n-1],其中B中的元素B[i]=A[0]×A[1]×…×A[i-1]×A[i+1]×…×A[n-1],不能使用除法。

實現

public class Solution52 {
    public int[] multiply(int[] nums){
        if(nums==null || nums.length<2){
            return null;
        }
        int[] result=new int[nums.length];
        result[0]=1;
        for(int i=1;i<nums.length;i++){
            result[i]=result[i-1]*nums[i-1];
        }
        int temp=1;
        for(int i=nums.length-2;i>=0;i--){
            temp*=nums[i+1];
            result[i]*=temp;
        }
        return result;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章