LeetCode 360. Sort Transformed Array

原题链接在这里:https://leetcode.com/problems/sort-transformed-array/description/

题目:

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

题解:

如果a > 0, 左右两边的点就比中间的点大. two pointers夹比, 从大往小赋值.

a < 0, 左右两边的点比中间的点小. two pointers夹比, 从小往大赋值.

Time Complexity: O(n). n = nums.length.

Space: O(1). regardless res.

AC Java:

 1 class Solution {
 2     public int[] sortTransformedArray(int[] nums, int a, int b, int c) {
 3         if(nums == null || nums.length == 0){
 4             return nums;
 5         }
 6         
 7         int [] res = new int[nums.length];
 8         int l = 0;
 9         int r = nums.length-1;
10         int index = a >=0 ? nums.length-1 : 0;
11         
12         while(l <= r){
13             int lNum = quad(nums[l], a, b, c);
14             int rNum = quad(nums[r], a, b, c);
15             if(a>=0){
16                 if(lNum > rNum){
17                     res[index--] = lNum;
18                     l++;
19                 }else{
20                     res[index--] = rNum;
21                     r--;
22                 }
23             }else{
24                 if(lNum > rNum){
25                     res[index++] = rNum;
26                     r--;
27                 }else{
28                     res[index++] = lNum;
29                     l++;
30                 }
31             }
32         }
33         
34         return res;
35     }
36     
37     private int quad(int x, int a, int b, int c){
38         return a*x*x + b*x + c;
39     }
40 }

类似Squares of a Sorted Array.

posted @ 2018-02-18 08:17  Dylan_Java_NYC  阅读(361)  评论(0编辑  收藏  举报