Simple Java solution O(n) without extra space


  • 1
    D
    public class Solution {
        public int[] productExceptSelf(int[] nums) {
            int[] result = new int[nums.length];
            int l = 1;
            int r = 1;
            for(int j = 0;j<result.length;j++) {
                result[j] = 1;
            }
            for(int i = 0;i<nums.length-1;i++) {
                l *= nums[i];
                int rIndex = nums.length - i - 1;
                r *= nums[rIndex];
                result[i+1] *= l;
                result[rIndex -1] *= r;
            }
            
            return result;
        }
    }

  • 0
    A
    This post is deleted!

  • -2
    N

    public class Solution {
    public int[] productExceptSelf(int[] nums) {

    	int[] result = new int[10];
    	
    	
    	for (int i = 0; i < nums.length; i++) {
    		result[i] = 1;
    		for (int j = 0; j < nums.length; j++) {
    			if (j == i) {
    				continue;
    			} else {
    				
    				result[i] *= nums[j];
    			}
    			
    			
    		}
    		System.out.println(result[i]);
    	}
        return result;
    }
    
    public static void main(String[] args)
    {
        int[] a = { 1, 2, 3, 4,5 };
        Solution s = new Solution();
        int[] res = s.productExceptSelf(a);
        Arrays.toString(res);
        
    }
    

    }


  • 0
    R

    This is a O(n2) solution!


Log in to reply
 

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