-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy path0360-sort-transformed-array.js
More file actions
52 lines (47 loc) · 1.17 KB
/
0360-sort-transformed-array.js
File metadata and controls
52 lines (47 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* 360. Sort Transformed Array
* https://leetcode.com/problems/sort-transformed-array/
* Difficulty: Medium
*
* Given a sorted integer array nums and three integers a, b and c, apply a quadratic function
* of the form f(x) = ax2 + bx + c to each element nums[i] in the array, and return the array
* in a sorted order.
*/
/**
* @param {number[]} nums
* @param {number} a
* @param {number} b
* @param {number} c
* @return {number[]}
*/
var sortTransformedArray = function(nums, a, b, c) {
const result = new Array(nums.length);
let left = 0;
let right = nums.length - 1;
let index = a >= 0 ? nums.length - 1 : 0;
while (left <= right) {
const leftVal = transform(nums[left]);
const rightVal = transform(nums[right]);
if (a >= 0) {
if (leftVal > rightVal) {
result[index--] = leftVal;
left++;
} else {
result[index--] = rightVal;
right--;
}
} else {
if (leftVal < rightVal) {
result[index++] = leftVal;
left++;
} else {
result[index++] = rightVal;
right--;
}
}
}
return result;
function transform(x) {
return a * x * x + b * x + c;
}
};