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]

参考:https://discuss.leetcode.com/topic/48424/java-o-n-incredibly-short-yet-easy-to-understand-ac-solution

the problem seems to have many cases a>0, a=0,a<0, (when a=0, b>0, b<0). However, they can be combined into just 2 cases: a>0 or a<0

1.a>0, two ends in original array are bigger than center if you learned middle school math before.

2.a<0, center is bigger than two ends.

so 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. For a==0 case, it does not matter what b's sign is.
The function is monotonically increasing or decreasing. you can start with either beginning or end.

 public class Solution {
public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
int[] res = new int[nums.length];
int l=0, r=nums.length-1;
int index = a<0? 0 : nums.length-1;
while (l <= r) {
if (a < 0) {
res[index++] = calc(nums[l], a, b, c)<calc(nums[r], a, b, c)? calc(nums[l++], a, b, c) : calc(nums[r--], a, b, c);
}
else {
res[index--] = calc(nums[l], a, b, c)>calc(nums[r], a, b, c)? calc(nums[l++], a, b, c) : calc(nums[r--], a, b, c);
}
}
return res;
} public int calc(int n, int a, int b, int c) {
return a*n*n+b*n+c;
}
}

最新文章

  1. Lind.DDD~实体属性变更追踪器的实现
  2. ActiveMQ 即时通讯服务 浅析
  3. 转载《Android Handler、Message》
  4. Hasor-Core v0.0.4 &amp; Web v0.0.3 发布
  5. Linux安装卸载查看vsftpd
  6. frame中隐藏横向滚动条
  7. (03)odoo模型/记录集/公用操作
  8. MySQL – optimizer_search_depth
  9. JSP+Servlet+JavaBean
  10. ASP.NET Core 行军记 -----拔营启程
  11. 第二百八十一、二、三天 how can I 坚持
  12. 使用hibernate tools插件生成POJO
  13. QLGame 2d Engine 搭建2d游戏原理
  14. HTML5 File api 实现断点续传
  15. 为什么Android AsyncTask的使用要遵循五大原则
  16. 32位程序在64位系统上获取系统安装时间(要使用KEY_WOW64_64KEY标记)
  17. 微软MSBI商业智能视频
  18. iOS--通过MOB平台实现第三方登录与分享
  19. Android源码分析二 硬件抽象层(HAL)
  20. autocomplate 学习

热门文章

  1. 命名函数、eval创建局部变量
  2. 请问MVC4是不是类似于html页+ashx页之间用JSON通过AJAX交换数据这种方式、?
  3. NOIP2014 uoj20解方程 数论(同余)
  4. TEST===&gt;Sqlserver中获取年月日时分秒
  5. 一些简单编程练习题P【持续更新】
  6. spark 2.0 Vector toBreeze
  7. vs 调试的时候 使用IP地址,局域网的设备可以访问并调试
  8. SQLite的原子提交原理
  9. c# winform编程之多线程ui界面资源修改总结篇
  10. LoadRunner使用技巧-IP欺骗的使用