zoukankan      html  css  js  c++  java
  • Leetcode: 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]

    参考: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.

     1 public class Solution {
     2     public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
     3         int[] res = new int[nums.length];
     4         int l=0, r=nums.length-1;
     5         int index = a<0? 0 : nums.length-1;
     6         while (l <= r) {
     7             if (a < 0) {
     8                 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);
     9             }
    10             else {
    11                 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);
    12             }
    13         }
    14         return res;
    15     }
    16     
    17     public int calc(int n, int a, int b, int c) {
    18         return a*n*n+b*n+c; 
    19     }
    20 }
  • 相关阅读:
    ##微信登陆,给大家分享一个第三方登陆
    ##Solr的各种版本下载
    ##redis在linux上的安装详解
    ##activeMq的简介与安装
    ##Springboot框架--配置文件介绍
    论面向服务架构及其应用
    MVC架构模式
    第八周总结
    细化架构阅读笔记
    第五周总结
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/6186389.html
Copyright © 2011-2022 走看看