If a <0, the maximum value is at the array's vertex. So we need to move the two end pointers toward the vertex but output from left to right.
1: class Solution {
2: public:
3: vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) {
4: int start = 0, end = nums.size()-1;
5: int i = a >= 0 ? nums.size()-1 : 0;
6: vector<int> res(nums.size(), 0);
7: while (start <= end) {
8: int startNum = computeNumber(nums[start], a, b, c);
9: int endNum = computeNumber(nums[end], a, b, c);
10: if (a >= 0) {
11: if (startNum >= endNum) { res[i--] = startNum; start++; }
12: else { res[i--] = endNum; end--; }
13: } else {
14: if (startNum <= endNum) { res[i++] = startNum; start++; }
15: else { res[i++] = endNum; end--; }
16: }
17: }
18: return res;
19: }
20: int computeNumber(int n, int a, int b, int c) {
21: return a*n*n+b*n+c;
22: }
23: };
No comments:
Post a Comment