概述: 老样子,通过分析具体的算法题来学习算法。
LeetCode 977: 有序数组的平方
在此介绍两种方法来解决问题:
暴力法快速排序
(1)利用原来的数组直接完成平方运算
(2)对升级后的数组调用 Arrays.sort() 方法快速排序
(3)返回数组
class Solution {
public int[] sortedSquares(int[] nums) {
//暴力法之原地升级
for(int i = 0; i < nums.length; i++){
nums[i] = nums[i] * nums[i];
}
//sort排序
Arrays.sort(nums);
return nums;
}
}
双指针
(1)根据题意可知,这是一个递增数组,返回的数组也是递增数组
(2)设置两个指针,一个在数组的开头,一个在数组的结尾
(3)创建一个一维数组保存结果集
(4)对于较大值出现的位置只可能在两边,所有通过两边的数值平方和不断比较,不断获得相对最大值
(5)再创建一个指针,将最大值从后向前保存到结果集数组中
class Solution {
public int[] sortedSquares(int[] nums) {
//设置左右指针 和 结果集指针
int left = 0, right = nums.length - 1;
int res = right;
//设置一个数组保存结果集
int [] result = new int [nums.length];
//遍历数组,left指针右移,right指针左移
while(left <= right){
if(nums[left] * nums[left] > nums[right] * nums[right]){
result[res] = nums[left] * nums[left];
res--;
left++;
}else{
result[res] = nums[right] * nums[right];
res--;
right--;
}
}
return result;
}
}