摘要:題目解答還是數(shù)學(xué)解法,根據(jù)這個(gè)方程圖形的特征來(lái)判斷最大最小值的取向
題目:
Given a sorted array of integers nums and integer values a, b and c. Apply a function of the form f(x) = ax2 + bx + c to each element x in the array.
The returned array must be in sorted order.
Expected time complexity: O(n)
Example:
nums = [-4, -2, 2, 4], a = 1, b = 3, c = 5,
Result: [3, 9, 15, 33]
nums = [-4, -2, 2, 4], a = -1, b = 3, c = 5
Result: [-23, -5, 1, 7]
解答:
//還是數(shù)學(xué)解法,根據(jù)這個(gè)方程圖形的特征來(lái)判斷最大最小值的取向 public int function(int num, int a, int b, int c) { return a * num * num + b * num + c; } public int[] sortTransformedArray(int[] nums, int a, int b, int c) { int len = nums.length; int[] result = new int[len]; int index = a >= 0 ? len - 1 : 0; int i = 0, j = len - 1; while (i <= j) { if (a >= 0) { result[index--] = function(nums[i], a, b, c) >= function(nums[j], a, b, c) ? function(nums[i++], a, b, c) : function(nums[j--], a, b, c); } else { result[index++] = function(nums[i], a, b, c) <= function(nums[j], a, b, c) ? function(nums[i++], a, b, c) : function(nums[j--], a, b, c); } } return result; }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://m.hztianpu.com/yun/64928.html
摘要:題目鏈接這是個(gè)數(shù)學(xué)問(wèn)題,拋物線(xiàn),我們知道這時(shí)候是個(gè)凹函數(shù),兩遍的值大于中間,所以從兩遍開(kāi)始哪邊的大就把結(jié)果放到的右邊這時(shí)候是個(gè)凸函數(shù),兩遍的值小于中間,所以?xún)杀殚_(kāi)始掃哪邊的值小就把它放到的左邊這時(shí)候是單調(diào)增的函數(shù),用上面任意一種方法都可以。 360. Sort Transformed Array 題目鏈接:https://leetcode.com/problems... 這是個(gè)數(shù)學(xué)問(wèn)題...
閱讀 928·2023-04-25 23:59
閱讀 3868·2021-10-08 10:04
閱讀 1750·2019-08-30 14:05
閱讀 1079·2019-08-30 13:58
閱讀 554·2019-08-29 18:41
閱讀 1182·2019-08-29 17:15
閱讀 2381·2019-08-29 14:13
閱讀 2803·2019-08-29 13:27