LeetCode 360: Sort Transformed Array Solution
Master LeetCode problem 360 (Sort Transformed Array), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
360. Sort Transformed Array
Problem Explanation
Explanation:
To solve this problem, we can follow these steps:
- Calculate the transformation of each element in the input array based on the given coefficients and constant value.
- Store these transformed values in a new array and sort it.
- Return the sorted transformed array.
Time complexity analysis:
- Calculating the transformed values takes O(n) time.
- Sorting the transformed array takes O(n log n) time.
- Overall time complexity: O(n log n)
Space complexity analysis:
- We use an extra array to store the transformed values, so the space complexity is O(n).
:
Solution Code
class Solution {
public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
int n = nums.length;
int[] result = new int[n];
int left = 0, right = n - 1;
int index = a >= 0 ? n - 1 : 0;
while (left <= right) {
int leftVal = calculate(nums[left], a, b, c);
int rightVal = calculate(nums[right], a, b, c);
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;
}
private int calculate(int x, int a, int b, int c) {
return a * x * x + b * x + c;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 360 (Sort Transformed Array)?
This page provides optimized solutions for LeetCode problem 360 (Sort Transformed Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 360 (Sort Transformed Array)?
The time complexity for LeetCode 360 (Sort Transformed Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 360 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 360 in Java, C++, or Python.