1. 程式人生 > >leetcode (Maximum Product of Three Numbers)

leetcode (Maximum Product of Three Numbers)

Title:Maximum Product of Three Numbers    605

Difficulty:Easy

原題leetcode地址:https://leetcode.com/problems/can-place-flowers/

 

1. 注意兩個負數的乘積為正數

時間複雜度:O(n),一次一層for迴圈,最長遍歷整個陣列的長度。

空間複雜度:O(1),沒有申請空間。

    /**
     * 1. 3個正數相乘,或者2個負數和一個正數相乘,最後比較他們的結果
     * @param nums
     * @return
     */
    public static int maximumProduct(int[] nums) {

        if (nums == null || nums.length < 3) {
            return 0;
        }

        int firstMaxPositive = Integer.MIN_VALUE;
        int secondMaxPositive = Integer.MIN_VALUE;
        int thirdMaxPositive = Integer.MIN_VALUE;
        int firstMinNegative = Integer.MAX_VALUE;
        int secondMinNegative = Integer.MAX_VALUE;

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > firstMaxPositive) {
                thirdMaxPositive = secondMaxPositive;
                secondMaxPositive = firstMaxPositive;
                firstMaxPositive = nums[i];
            }
            else if (nums[i] > secondMaxPositive) {
                thirdMaxPositive = secondMaxPositive;
                secondMaxPositive = nums[i];
            }
            else if (nums[i] > thirdMaxPositive) {
                thirdMaxPositive = nums[i];
            }

            if (nums[i] < firstMinNegative) {
                secondMinNegative = firstMinNegative;
                firstMinNegative = nums[i];
            }
            else if (nums[i] < secondMinNegative) {
                secondMinNegative = nums[i];
            }
        }

        return Math.max(firstMaxPositive * secondMaxPositive * thirdMaxPositive,
                firstMaxPositive * firstMinNegative * secondMinNegative);

    }

2. 先排序,在比較

時間複雜度:O(nlogn),給的是快排的時間複雜度,但是Java底層對排序的演算法時取決於陣列的長度。

空間複雜度:O(1),沒有申請空間。

    /**
     * 先排序,後比較
     * @param nums
     * @return
     */
    public static int maximumProduct1(int[] nums) {

        if (nums == null || nums.length < 3) {
            return 0;
        }

        Arrays.sort(nums);

        return Math.max(nums[nums.length - 1] * nums[nums.length - 2] * nums[nums.length - 3],
                nums[nums.length - 1] * nums[0] * nums[1]);

    }