LeetCode 360. Sort Transformed Array
2017-01-13 07:47
393 查看
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]
思路:
1. 这是一个数学题。计算所有x和对称轴的距离|x−b2a,当a<0,则距离越大,|f(x)| 越小;当a>0,距离越大,|f(x)| 越大;当a=0,f(x)=bx+c, b>=0,则f(x) monotonically increasing function, otherwise it’s non-increasing function.
2. 在实际计算中,不用计算|x−b2a|,因为不需要绝对值的大小,只需要相对大小即可,所以计算|2ax+b|即可。
3. 如何做到o(n)的复杂度?必须利用输入是sorted array这个条件。先计算所有距离,并根据a符号决定是找出最大值还是最小值的坐标,例如,a>0,则找出距离最小值的坐标,然后把这个值坐标对应的f(x) 计算出来放在输出array最左边,然后用two pointer的方法,从这个最小距离的坐标两侧移动,比较两侧的距离,并把相对小的距离的坐标的f(x) 输出!
4. 还可以继续简化,参考http://www.cnblogs.com/grandyang/p/5595614.html 不用计算并比较距离。可以只利用下面的性质,a>0则抛物线两边比中间大;a>0则抛物线中间比两边大;a=0则根据b来判断是单调递增还是递减。
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]
思路:
1. 这是一个数学题。计算所有x和对称轴的距离|x−b2a,当a<0,则距离越大,|f(x)| 越小;当a>0,距离越大,|f(x)| 越大;当a=0,f(x)=bx+c, b>=0,则f(x) monotonically increasing function, otherwise it’s non-increasing function.
2. 在实际计算中,不用计算|x−b2a|,因为不需要绝对值的大小,只需要相对大小即可,所以计算|2ax+b|即可。
3. 如何做到o(n)的复杂度?必须利用输入是sorted array这个条件。先计算所有距离,并根据a符号决定是找出最大值还是最小值的坐标,例如,a>0,则找出距离最小值的坐标,然后把这个值坐标对应的f(x) 计算出来放在输出array最左边,然后用two pointer的方法,从这个最小距离的坐标两侧移动,比较两侧的距离,并把相对小的距离的坐标的f(x) 输出!
4. 还可以继续简化,参考http://www.cnblogs.com/grandyang/p/5595614.html 不用计算并比较距离。可以只利用下面的性质,a>0则抛物线两边比中间大;a>0则抛物线中间比两边大;a=0则根据b来判断是单调递增还是递减。
vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) { int n=nums.size(); vector<int> res(n,0); for(int i=0;i<n;i++) nums[i]=a*x*x+b*x+c; int left=0,right=n-1; int index=a>=0?n-1:0; while(left<=right){ if(a>=0){ res[index--]=(nums[left]>=nums[right])?nums[left++]:nums[right--]; }else{ res[index++]=(nums[left]>=nums[right])?nums[right--]:nums[left++]; } } return res; }
相关文章推荐
- 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 变换数组排序
- Leetcode: Sort Transformed Array
- Sort Transformed Array -- LeetCode
- 360. Sort Transformed Array
- 360. Sort Transformed Array
- Sort Transformed Array
- leetcode.array--75. Sort Colors
- 【LeetCode】【Array】【75】Sort Colors
- leetcode media of an sort array
- Sort Transformed Array
- LeetCode88 Merge two sort array
- LeetCode刷题【Array】 Sort Colors
- [LeetCode]--242. Valid Anagram(Count table && char array sort())