算法——有序数组的平方
题目来源
给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
示例 1:
输入:nums = [-4,-1,0,3,10]
输出:[0,1,9,16,100]
解释:平方后,数组变为 [16,1,0,9,100],排序后,数组变为 [0,1,9,16,100]
示例 2:
输入:nums = [-7,-3,2,3,11]
输出:[4,9,9,49,121]
方法一:直接排序
复制代码
1
2
3
4
5
6
7
8
9
10
11class Solution { public int[] sortedSquares(int[] nums) { int[] ans = new int[nums.length]; for (int i = 0; i < nums.length; ++i) { ans[i] = nums[i] * nums[i]; } Arrays.sort(ans); return ans; } }
方法二:双指针
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31class Solution { public int[] sortedSquares(int[] nums) { int n = nums.length; int negative = -1; for (int i = 0; i < n; ++i) { if (nums[i] < 0) { negative = i; } else { break; } } int[] ans = new int[n]; int index = 0, i = negative, j = negative + 1; while (i >= 0 || j < n) { if (i < 0) { ans[index] = nums[j] * nums[j]; ++j; } else if (j == n) { ans[index] = nums[i] * nums[i]; --i; } else if (nums[i] * nums[i] < nums[j] * nums[j]) { ans[index] = nums[i] * nums[i]; --i; } else { ans[index] = nums[j] * nums[j]; ++j; } ++index; }
最后
以上就是合适煎饼最近收集整理的关于有序数组的平方(Java)的全部内容,更多相关有序数组内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复