LeetCode 360. Sort Transformed Array
2018-02-18 08:17
459 查看
原题链接在这里:https://leetcode.com/problems/sort-transformed-array/description/
题目:
Given a sorted array of integers nums and integer values a, b 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:
题解:
如果a > 0, 左右两边的点就比中间的点大. two pointers夹比, 从大往小赋值.
a < 0, 左右两边的点比中间的点小. two pointers夹比, 从小往大赋值.
Time Complexity: O(n). n = nums.length.
Space: O(1). regardless res.
AC Java:
题目:
Given a sorted array of integers nums and integer values a, b 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 }
相关文章推荐
- LeetCode 360. Sort Transformed Array
- Leetcode 360 Sort Transformed Array
- LeetCode 360. Sort Transformed Array(计算函数)
- [leetcode] 360. Sort Transformed Array 解题报告
- [Leetcode] 360. Sort Transformed Array 解题报告
- [LeetCode] 360. Sort Transformed Array 排序转换后的数组
- LeetCode 360. Sort Transformed Array
- Leetcode: Sort Transformed Array
- Sort Transformed Array -- LeetCode
- 360. Sort Transformed Array
- 360. Sort Transformed Array
- [LeetCode] Sort Transformed Array 变换数组排序
- Sort Transformed Array
- LeetCode刷题【Array】 Sort Colors
- leetcode.array--75. Sort Colors
- Sort Transformed Array
- 【LeetCode】【Array】【75】Sort Colors
- leetcode media of an sort array
- 【leetcode】Array——Sort Color(75)
- LeetCode88 Merge two sort array