Writen by go, can not accepted. O(n) time, no extra space


  • 0

    If something wrong, comment me, thanks.

    func productExceptSelf(nums []int) []int {
    	var (
    		r []int
    		i int
    		j int
    	)
    
    	r = append(r, nums[0])
    	for i = 1; i < len(nums)-1; i++ {
    		r = append(r, nums[i]*r[i-1])
    	}
    	r = append(r, r[i-1])
    
    	for j = len(nums) - 2; j > 0; j-- {
    		r[j] = r[j-1] * nums[j+1]
    		nums[j] *= nums[j+1]
    	}
    	r[0] = nums[j+1]
    
    	return r
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.