Skip to content

Commit 89c6381

Browse files
committed
Add solution #360
1 parent 54c12c8 commit 89c6381

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,7 @@
348348
357|[Count Numbers with Unique Digits](./solutions/0357-count-numbers-with-unique-digits.js)|Medium|
349349
358|[Rearrange String k Distance Apart](./solutions/0358-rearrange-string-k-distance-apart.js)|Hard|
350350
359|[Logger Rate Limiter](./solutions/0359-logger-rate-limiter.js)|Easy|
351+
360|[Sort Transformed Array](./solutions/0360-sort-transformed-array.js)|Medium|
351352
363|[Max Sum of Rectangle No Larger Than K](./solutions/0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard|
352353
365|[Water and Jug Problem](./solutions/0365-water-and-jug-problem.js)|Medium|
353354
367|[Valid Perfect Square](./solutions/0367-valid-perfect-square.js)|Easy|
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* 360. Sort Transformed Array
3+
* https://leetcode.com/problems/sort-transformed-array/
4+
* Difficulty: Medium
5+
*
6+
* Given a sorted integer array nums and three integers a, b and c, apply a quadratic function
7+
* of the form f(x) = ax2 + bx + c to each element nums[i] in the array, and return the array
8+
* in a sorted order.
9+
*/
10+
11+
/**
12+
* @param {number[]} nums
13+
* @param {number} a
14+
* @param {number} b
15+
* @param {number} c
16+
* @return {number[]}
17+
*/
18+
var sortTransformedArray = function(nums, a, b, c) {
19+
const result = new Array(nums.length);
20+
let left = 0;
21+
let right = nums.length - 1;
22+
let index = a >= 0 ? nums.length - 1 : 0;
23+
24+
while (left <= right) {
25+
const leftVal = transform(nums[left]);
26+
const rightVal = transform(nums[right]);
27+
28+
if (a >= 0) {
29+
if (leftVal > rightVal) {
30+
result[index--] = leftVal;
31+
left++;
32+
} else {
33+
result[index--] = rightVal;
34+
right--;
35+
}
36+
} else {
37+
if (leftVal < rightVal) {
38+
result[index++] = leftVal;
39+
left++;
40+
} else {
41+
result[index++] = rightVal;
42+
right--;
43+
}
44+
}
45+
}
46+
47+
return result;
48+
49+
function transform(x) {
50+
return a * x * x + b * x + c;
51+
}
52+
};

0 commit comments

Comments
 (0)