zoukankan      html  css  js  c++  java
  • Sort Transformed Array -- LeetCode

    Given a sorted array of integers nums and integer values ab 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]

    思路:因为是排好序的数组,我们用两个指针从数组两边向中间计算答案。根据每次计算的函数值的大小决定移动哪个指针。复杂度O(N)。

     1 class Solution {
     2 public:
     3     int f(int x, int a, int b, int c) {
     4         return a * x * x + b * x + c;
     5     }
     6     vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) {
     7         int len = nums.size();
     8         vector<int> res(len);
     9         int left = 0, right = nums.size() - 1, count = 0;
    10         while (left <= right) {
    11             int leftRes = f(nums[left], a, b, c);
    12             int rightRes = f(nums[right], a, b, c);
    13             bool goLeft = (a >= 0 && leftRes >= rightRes) || (a < 0 && leftRes <= rightRes);
    14             int curPos = (a >= 0 ? len - 1 - count : count);
    15             if (goLeft) {
    16                 res[curPos] = leftRes;
    17                 left++;
    18             } else {
    19                 res[curPos] = rightRes;
    20                 right--;
    21             }
    22             count++;
    23         }
    24         return res;
    25     }
    26 };
  • 相关阅读:
    git cherrypick 小结
    git 忽略机制
    git revert 小结
    git 忽略机制
    学习 原理图2 电源电路
    git merge 和 git rebase 小结
    git cherrypick 小结
    学习 原理图2 电源电路
    git revert 小结
    使用SMTP发送邮件
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5806327.html
Copyright © 2011-2022 走看看