360. Sort Transformed Array

Given a sorted array of integers nums and integer values a, b 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]
**解题思路 **
use two pointers i, j and do a merge-sort like process. depending on sign of a, you may want to start from the beginning or end of the transformed array.
- if a > 0 是U型的抛物线, 左右两端大,中间底部小
- if a < 0 是 n 型的, 左右两端小,中间顶部高


    public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
      int n = nums.length;
      int[] res = new int[n];
      int i = 0, j = n - 1;
      int index = a >= 0 ? n - 1 : 0;
      while (i <= j) {
          if (a >= 0) {
              res[index--] = quad(nums[i], a, b, c) >= quad(nums[j], a, b, c) ? quad(nums[i++], a, b, c) : quad(nums[j--], a, b,c);
          } else {
              res[index++] = quad(nums[i], a, b, c) >= quad(nums[j], a, b, c) ? quad(nums[j--], a, b, c) : quad(nums[i++], a, b, c);
          }
      }
      return res;
    }
    
    private int quad(int x, int a, int b, int c) {
        return a * x * x  + b * x + c;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,030评论 0 23
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,788评论 0 33
  • 1 分类: 技能:专业技能,要内化到肌肉,变成本能动作意识。 知识,叙事性的知识。 思维,即程序性,即算法,即编...
    freshriver阅读 230评论 0 0
  • 熙熙囔囔的人群中,百态众生,谁才是幸福的人呢? 那一瞬间,地铁里的每一个人都值得我羡慕。 有气质出众的中年妇人谈论...
    枕前发尽千般愿阅读 188评论 1 0
  • 群花纷妍,落英如雨。你,青绾瓷衣,抚悠悠琴声;我,白衣绿裳,舞翩翩姿态。雨,不期而至。你携我浅水行舟,许我以缱绻的...
    贪吃珂阅读 393评论 0 0